2013-08-26 39 views
10

我是一名新的Python用户。导入txt文件并将每行作为列表

我有一个txt文件,这将是这样的:

3,1,3,2,3 
3,2,2,3,2 
2,1,3,3,2,2 
1,2,2,3,3,1 
3,2,1,2,2,3 

,但可能不太或多行。

我想将每行导入为列表。

我知道你能做到这样:

filename = 'MyFile.txt' 
fin=open(filename,'r') 
L1list = fin.readline() 
L2list = fin.readline() 
L3list = fin.readline() 

但因为我不知道我有多少行会,有另一种方式来创建个人列表?

回答

22

不要创建单独的列表;创建列表列表:

results = [] 
with open('inputfile.txt') as inputfile: 
    for line in inputfile: 
     results.append(line.strip().split(',')) 

或者更好的是,使用csv module

import csv 

results = [] 
with open('inputfile.txt', newline='') as inputfile: 
    for row in csv.reader(inputfile): 
     results.append(row) 

列表或字典是 superiour结构,以保持从文件中读取的东西任意数量的轨道。

请注意,循环还可以让您单独处理数据行,而无需将文件的所有内容都读取到内存中;而不是使用results.append()只是在那里处理那条线。

只是为了完整性缘故,这里是一个班轮精简版本的CSV读取文件到列表中一气呵成:

import csv 

with open('inputfile.txt', newline='') as inputfile: 
    results = list(csv.reader(inputfile)) 
+0

'csv.reader(open(filename))'easy! –

4

创建一个列表的列表:

with open("/path/to/file") as file: 
    lines = [] 
    for line in file: 
     # The rstrip method gets rid of the "\n" at the end of each line 
     lines.append(line.rstrip().split(",")) 
+0

非常感谢,非常感谢。 – John

+0

嗨iCodez-我实际上正在尝试使用这个,当它列出一个列表时,列表中实际上只有一个项目 - 我现在使用的输入文件(如原始问题中引用的那样)有三行,所以应该有三个列表。使用你的方法,我只是得到[['3','2','1','2','3','1','2','3','1','2', '3','1','1','1','1','1','3','3','1','1','2','2','1' '3']。有什么想法吗?非常感谢。 – John

+0

@John - 我无法重现您的问题。我在你给出的5行示例上测试了我的代码,它的工作原理与它应有的一样。它列出了5个列表,每行一个。你确定这个文件有3行而不只是一行吗? – iCodez

2
with open('path/to/file') as infile: # try open('...', 'rb') as well 
    answer = [line.strip().split(',') for line in infile] 

如果你想要的数字为int s:

with open('path/to/file') as infile: 
    answer = [[int(i) for i in line.strip().split(',')] for line in infile] 
+0

谢谢!一个后续问题0我收到错误文件“seventeen_v2.3.py”,第7行,在 answer = [[int(i)for line in line.strip()。split(',') ] for line in infile] ValueError:int()与基数为10的无效文字:'1 \ r1' txt文件只包含数字 - 任何想法为什么python将此“\ r1”添加到输入? – John

+0

检查编辑 – inspectorG4dget

-1
lines=[] 
with open('file') as file: 
    lines.append(file.readline()) 
+1

您需要提供更完整的答案。就目前来看,这不符合OP的要求。 – iCodez

相关问题