Python 导入txt文件并将每一行作为列表

Python 导入txt文件并将每一行作为列表,python,list,python-3.x,file-io,Python,List,Python 3.x,File Io,我是Python的新用户 我有一个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() 但是因为我不知道我会

我是Python的新用户

我有一个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()

但是因为我不知道我会有多少行,有没有其他方法来创建单独的列表?

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

results = []
with open('inputfile.txt') as inputfile:
    for line in inputfile:
        results.append(line.strip().split(','))
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(","))
或者更好地使用:

列表或词典在跟踪从文件中读取的任意数量的内容方面远远优于我们的结构

请注意,任何一个循环都允许您单独寻址数据行,而无需将文件的所有内容读入内存;不要使用
results.append()
只需在此处处理该行即可

为了完整起见,这里有一个单行压缩版本,可以一次性将CSV文件读入列表:

import csv

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

创建列表列表:

results = []
with open('inputfile.txt') as inputfile:
    for line in inputfile:
        results.append(line.strip().split(','))
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(","))
如果您希望数字为
int
s:

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

你需要给出一个更完整的答案。就目前而言,这并不是OP想要的。谢谢!一个后续问题-0我得到了错误文件“seventive_v2.3.py”,第7行,在回答中=[[int(I)代表行中的I.strip().split(',')]代表行中的填充]ValueError:int()的无效文本以10为基数:“1\r1”txt文件中只有数字-知道python为什么要添加这个“\r1”吗输入?Hi iCodez-我实际上在尝试使用它,当它制作列表时,列表中实际上只有一项-我现在使用的输入文件(如原始问题中所引用)有三行,因此应该有三个列表。使用你的方法,我得到的只是['3','2','1','2','3','1','2','3','3','1','1','1','1','3','3','1','1','2','2','1','3']。有什么想法吗?非常感谢。@John-我无法重现你的问题。我在您给出的5行示例中测试了我的代码,它的工作原理与它应该的一样。它列出了5个列表,每行一个。你确定这个文件有三行而不是一行吗?@John-另外,我会看看Pieters答案上解释
打开
内置的评论。也许这可以解决你的问题。谢谢iCodez-这确实是我这边的一个问题。我使用了两个版本的test.txt文件,但指向了错误的版本…感谢您的耐心和帮助@约翰-非常乐意帮忙!不过,别忘了接受答案(点击勾号)以保持整洁有序(所有没有接受答案的问题都会保留在“未回答”栏中)。
lines=[]
with open('file') as file:
   lines.append(file.readline())