如何使用Python将文本文件读取到列表或数组中

如何使用Python将文本文件读取到列表或数组中

问题描述:

我正在尝试将文本文件的行读入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.

文本文件的格式如下:

0,0,200,0,53,1,0,255,...,0.

...在上面,实际的文本文件中还有数百或数千个项目.

Where the ... is above, there actual text file has hundreds or thousands more items.

我正在使用以下代码尝试将文件读入列表:

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()

我得到的输出是:

['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?

python的file.readlines()方法返回文件中的行列表:

f = open('file_name.ext', 'r')
x = f.readlines()
f.close()

现在,您应该可以遍历第x行的数组.

Now you should be able to iterate through the array of lines x.

如果您要使用该文件,而不必记住以后要关闭它,请执行以下操作:

If you want to use the file and not have to remember to close it afterward, do this:

with open('file_name.ext', 'r') as f:
    x = f.read().splitlines()