python读取文件提取数字问题

现有一多行数字组成的txt文件,数字之间由空格隔开,如何使用python将数字提取到一个【】形式的list中,我只能用readline()和split将数字存到【【】,【】,【】】这种形式的list中,求解。。

使用readlines()函数可以获取到一个长度为该文件总行数的列表,在此列表中每一行都是一个由空格分隔的数字组成的字符串。所以对于这样的处理我们只需要

循环处理该列表中的每一个元素即可。

源文件:
1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19

20 21 22

Python代码:

coding:utf-8

import sys

reload(sys)
sys.setdefaultencoding('utf8')

def getList(filename):
file = open(filename,'rb')
numberlist = file.readlines()
file.close()
return numberlist

def split4list(numberlist):
totallist = []
for item in numberlist:
sublist = item.strip('\n').strip('\r').split(' ')
for i in sublist:
totallist.append(i)
return totallist

if name =="__main__":
filename = './example.txt'
numberlist = getList(filename)
totallist = split4list(numberlist)

print totallist

本人所得结果:
D:\Software\Python2\python.exe E:/Code/Python/DataStructor/temp/temp.py
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22']

Process finished with exit code 0

结语:
使用Python分割的时候记得灵活使用split函数哦,希望这次的代码能帮到你。
:-)