一个文本文件 test txt的一行存储5个整数如下,1,3,56,67,34,数字直接用空格隔开,
要读出这些整数,如何用函数实现。
txt文件和python文件在同一目录下
with open('1.txt','r') as f:
file_str = f.read()
data = [int(i) for i in file_str.split() if i]
print(data)
#文件内容:
1 4 6 3 2
5 4 3 8 9 1
7 4 3
#程序
def readC(filename):
with open(filename) as f:
con = map(lambda x: list(map(int, x)), map(lambda x: x.replace("\n", "").split(), f.readlines()))
return list(con)
con = readC(filename)
print(con)
#--result
[[1, 4, 6, 3, 2], [5, 4, 3, 8, 9, 1], [7, 4, 3]]