如何使用 Python 将文本文件读入列表或数组 [英] How to read a text file into a list or an array with 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?
推荐答案
您必须使用 split()
所以,
lines = text_file.read().split(',')
我没有意识到这会有如此大的吸引力.这是一种更惯用的方法.
I didn't realise there would be so much traction to this. Here's a more idiomatic approach.
import csv
with open('filename.csv', 'r') as fd:
reader = csv.reader(fd)
for row in reader:
# do something
这篇关于如何使用 Python 将文本文件读入列表或数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!