python3讀取文件中的多行整數,每行有若干整數用空格隔開。python3本身沒有直接讀取int的接口,只能讀取字符串,因此需要自己編寫代碼。
讀取的文件如下形式:
1 2 3
1
4 5 6 7
1 8
9 10
11 6 12 13 14 15 16
1 3 7
17 18
11 6 19 20 21 22 23 24
1 25 3
26 3
11 27 6 3 28 7 29 30 31 32 33 34 35 36 37
6 2 38
39 11 27 1 40 6 41 42 43 44 45 46 47 3 48 7 49 50 51
52 6 3 53
54 1 6 55
11 6 56 57 58 59 60 61 62 63 64
3
1 65 66 67 68 3
69 11 1 6
編寫代碼如下:
def readIntList(filename): #返回整數的list列表
numbers = []
with open(filename, 'r', encoding='utf-8') as f:
while True:
line = f.readline()
if not line:#讀完了就返回
break
line = line.split()
#print(line)
for i in line:
numbers.append(int(i))
return numbers
numbers = readIntList('./data/kosarak.dat')
print(len(numbers))