如何读取文本文件导入列表或数组与Python [英] How to read text file into a list or array with Python
问题描述
我想一个文本文件的行读入蟒蛇列表或数组。我只需要能够在创建后在列表或数组单独访问任何项目。
I am trying to read the lines of a text file into a list or array in python. I just need to be able to individually access any item in the list or array after it is created.
该文本文件的格式如下:
The text file is formatted as follows:
0,0,200,0,53,1,0,255,...,0.
凡 ...
是上面有实际的文本文件中有数百或数千项。
Where the ...
is above, there actual text file has hundreds or thousands more items.
我用下面的code尝试读取文件到列表:
I'm using the following code to try to read the file into a list:
text_file = open("filename.dat", "r")
lines = text_file.readlines()
print lines
print len(lines)
text_file.close()
我得到的输出是:
The output I get is:
['0,0,200,0,53,1,0,255,...,0.']
1
显然,它是读取整个文件到只有一个项目的列表,而不是单独的项目的列表。我在做什么错了?
Apparently it is reading the entire file into a list of just one item, rather than a list of individual items. What am I doing wrong?
推荐答案
您将有您的字符串拆分为使用拆分值的列表()
You will have to split your string into a list of values using split()
因此,
lines = text_file.read().split(',')
这篇关于如何读取文本文件导入列表或数组与Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!