如何使用Python将文本文件读取到列表或数组中 [英] How to read a text file into a list or an array with Python

查看:1120
本文介绍了如何使用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()

这篇关于如何使用Python将文本文件读取到列表或数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆