Python 如何将文件逐行读入列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3277503/
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-18 09:23:08  来源:igfitidea点击:

How to read a file line-by-line into a list?

pythonstringfilereadlines

提问by Julie Raswick

How do I read every line of a file in Python and store each line as an element in a list?

如何在 Python 中读取文件的每一行并将每一行作为元素存储在列表中?

I want to read the file line by line and append each line to the end of the list.

我想逐行读取文件并将每一行附加到列表的末尾。

回答by Noctis Skytower

This will yield an "array" of lines from the file.

这将从文件中产生一个“数组”的行。

lines = tuple(open(filename, 'r'))

openreturns a file which can be iterated over. When you iterate over a file, you get the lines from that file. tuplecan take an iterator and instantiate a tuple instance for you from the iterator that you give it. linesis a tuple created from the lines of the file.

open返回一个可以迭代的文件。当您迭代一个文件时,您会从该文件中获取行。tuple可以使用迭代器并从您提供的迭代器中为您实例化一个元组实例。lines是从文件的行创建的元组。

回答by robert

This is more explicit than necessary, but does what you want.

这比必要的更明确,但可以满足您的需求。

with open("file.txt") as file_in:
    lines = []
    for line in file_in:
        lines.append(line)

回答by Felix Kling

See Input and Ouput:

请参阅输入和输出

with open('filename') as f:
    lines = f.readlines()

or with stripping the newline character:

或剥离换行符:

with open('filename') as f:
    lines = [line.rstrip() for line in f]

回答by SilentGhost

with open(filename) as f:
    content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content] 

回答by atomh33ls

Another option is numpy.genfromtxt, for example:

另一种选择是numpy.genfromtxt,例如:

import numpy as np
data = np.genfromtxt("yourfile.dat",delimiter="\n")

This will make dataa NumPy array with as many rows as are in your file.

这将使dataNumPy 数组的行数与文件中的行数相同。

回答by oliland

If you'd like to read a file from the command line or from stdin, you can also use the fileinputmodule:

如果您想从命令行或标准输入读取文件,您还可以使用该fileinput模块:

# reader.py
import fileinput

content = []
for line in fileinput.input():
    content.append(line.strip())

fileinput.close()

Pass files to it like so:

像这样将文件传递给它:

$ python reader.py textfile.txt 

Read more here: http://docs.python.org/2/library/fileinput.html

在此处阅读更多信息:http: //docs.python.org/2/library/fileinput.html

回答by moldovean

f = open("your_file.txt",'r')
out = f.readlines() # will append in the list out

Now variable out is a list (array) of what you want. You could either do:

现在变量 out 是您想要的列表(数组)。你可以这样做:

for line in out:
    print (line)

Or:

或者:

for line in f:
    print (line)

You'll get the same results.

你会得到同样的结果。

回答by Eneko Alonso

If you want the \nincluded:

如果你想要\n包括:

with open(fname) as f:
    content = f.readlines()

If you do not want \nincluded:

如果您不想\n包含:

with open(fname) as f:
    content = f.read().splitlines()

回答by user1833244

Here's one more option by using list comprehensions on files;

这是对文件使用列表推导式的另一种选择;

lines = [line.rstrip() for line in open('file.txt')]

This should be more efficient way as the most of the work is done inside the Python interpreter.

这应该是更有效的方式,因为大部分工作是在 Python 解释器中完成的。

回答by Johnny

Clean and Pythonic Way of Reading the Lines of a File Into a List

将文件的行读入列表的干净和 Pythonic 方式



First and foremost, you should focus on opening your file and reading its contents in an efficient and pythonic way. Here is an example of the way I personally DO NOT prefer:

首先,您应该专注于以高效和 Pythonic 的方式打开文件并阅读其内容。这是我个人不喜欢的方式的一个例子:

infile = open('my_file.txt', 'r')  # Open the file for reading.

data = infile.read()  # Read the contents of the file.

infile.close()  # Close the file since we're done using it.

Instead, I prefer the below method of opening files for both reading and writing as it is very clean, and does not require an extra step of closing the file once you are done using it. In the statement below, we're opening the file for reading, and assigning it to the variable 'infile.' Once the code within this statement has finished running, the file will be automatically closed.

相反,我更喜欢下面的打开文件进行读取和写入的方法,因为它非常干净,并且在使用完文件后不需要关闭文件的额外步骤。在下面的语句中,我们打开文件进行读取,并将其分配给变量“infile”。一旦此语句中的代码运行完毕,文件将自动关闭。

# Open the file for reading.
with open('my_file.txt', 'r') as infile:

    data = infile.read()  # Read the contents of the file into memory.

Now we need to focus on bringing this data into a Python Listbecause they are iterable, efficient, and flexible. In your case, the desired goal is to bring each line of the text file into a separate element. To accomplish this, we will use the splitlines()method as follows:

现在我们需要专注于将这些数据放入Python List 中,因为它们可迭代、高效且灵活。在您的情况下,所需的目标是将文本文件的每一行都放入一个单独的元素中。为此,我们将使用splitlines()方法,如下所示:

# Return a list of the lines, breaking at line boundaries.
my_list = data.splitlines()


The Final Product:

最终产品:

# Open the file for reading.
with open('my_file.txt', 'r') as infile:

    data = infile.read()  # Read the contents of the file into memory.

# Return a list of the lines, breaking at line boundaries.
my_list = data.splitlines()

Testing Our Code:

测试我们的代码:

  • Contents of the text file:
  • 文本文件的内容:
     A fost odat? ca-n povesti,
     A fost ca niciodat?,
     Din rude m?ri ?mp?r?testi,
     O prea frumoas? fat?.
  • Print statements for testing purposes:
  • 出于测试目的打印语句:
    print my_list  # Print the list.

    # Print each line in the list.
    for line in my_list:
        print line

    # Print the fourth element in this list.
    print my_list[3]
  • Output (different-looking because of unicode characters):
  • 输出(由于 unicode 字符而看起来不同):
     ['A fost odat\xc3\xa3 ca-n povesti,', 'A fost ca niciodat\xc3\xa3,',
     'Din rude m\xc3\xa3ri \xc3\xaemp\xc3\xa3r\xc3\xa3testi,', 'O prea
     frumoas\xc3\xa3 fat\xc3\xa3.']

     A fost odat? ca-n povesti, A fost ca niciodat?, Din rude m?ri
     ?mp?r?testi, O prea frumoas? fat?.

     O prea frumoas? fat?.