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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18448847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:47:29  来源:igfitidea点击:

Import txt file and having each line as a list

pythonlistpython-3.xfile-io

提问by John

I'm a new Python user.

我是一个新的 Python 用户。

I have a txt file that will be something like:

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

but may be less or more lines.

但可能更少或更多行。

I want to import each line as a list.

我想将每一行作为列表导入。

I know you can do it as such:

我知道你可以这样做:

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

but since I don't know how many lines I will have, is there another way to create individual lists?

但由于我不知道我将有多少行,是否有另一种方法来创建单独的列表?

回答by Martijn Pieters

Do not create separate lists; create a list of lists:

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

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

or better still, use the csvmodule:

或者更好的是,使用csv模块

import csv

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

Lists or dictionaries are farsuperiour structures to keep track of an arbitrary number of things read from a file.

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

Note that either loop also lets you address the rows of data individually without having to read all the contents of the file into memory either; instead of using results.append()just process that line right there.

请注意,任一循环还允许您单独寻址数据行,而不必将文件的所有内容读入内存;而不是使用results.append()就在那里处理那条线。

Just for completeness sake, here's the one-liner compact version to read in a CSV file into a list in one go:

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

import csv

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

回答by Martijn Pieters

Create a list of lists:

创建列表列表:

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

回答by inspectorG4dget

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

If you want the numbers as ints:

如果您希望数字为ints:

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

回答by corvid

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