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

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


当前回答

根据Python的文件对象方法,将文本文件转换为列表的最简单方法是:

with open('file.txt') as f:
    my_list = list(f)
    # my_list = [x.rstrip() for x in f] # remove line breaks

演示


如果只需要遍历文本文件行,可以使用:

with open('file.txt') as f:
    for line in f:
       ...

旧答案:

使用with和readline():

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

如果您不关心关闭文件,这一行程序将起作用:

lines = open('file.txt').readlines()

传统方式:

f = open('file.txt') # Open file on read mode
lines = f.read().splitlines() # List with stripped line-breaks
f.close() # Close file

其他回答

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

现在,变量out是您想要的列表(数组)。您可以选择:

for line in out:
    print (line)

Or:

for line in f:
    print (line)

你会得到同样的结果。

您也可以在NumPy中使用loadtxt命令。这比genfromttxt检查的条件更少,因此可能更快。

import numpy
data = numpy.loadtxt(filename, delimiter="\n")

这比必要的更明确,但可以做到你想要的。

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

具有文本文件内容:

line 1
line 2
line 3

我们可以在上面txt的同一目录中使用此Python脚本

>>> with open("myfile.txt", encoding="utf-8") as file:
...     x = [l.rstrip("\n") for l in file]
>>> x
['line 1','line 2','line 3']

使用追加:

x = []
with open("myfile.txt") as file:
    for l in file:
        x.append(l.strip())

Or:

>>> x = open("myfile.txt").read().splitlines()
>>> x
['line 1', 'line 2', 'line 3']

Or:

>>> x = open("myfile.txt").readlines()
>>> x
['linea 1\n', 'line 2\n', 'line 3\n']

Or:

def print_output(lines_in_textfile):
    print("lines_in_textfile =", lines_in_textfile)

y = [x.rstrip() for x in open("001.txt")]
print_output(y)

with open('001.txt', 'r', encoding='utf-8') as file:
    file = file.read().splitlines()
    print_output(file)

with open('001.txt', 'r', encoding='utf-8') as file:
    file = [x.rstrip("\n") for x in file]
    print_output(file)

输出:

lines_in_textfile = ['line 1', 'line 2', 'line 3']
lines_in_textfile = ['line 1', 'line 2', 'line 3']
lines_in_textfile = ['line 1', 'line 2', 'line 3']

使用Python 2和Python 3读写文本文件;它适用于Unicode

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Define data
lines = ['     A first string  ',
         'A Unicode sample: €',
         'German: äöüß']

# Write text file
with open('file.txt', 'w') as fp:
    fp.write('\n'.join(lines))

# Read text file
with open('file.txt', 'r') as fp:
    read_lines = fp.readlines()
    read_lines = [line.rstrip('\n') for line in read_lines]

print(lines == read_lines)

注意事项:

with是所谓的上下文管理器。它确保打开的文件再次关闭。这里的所有解决方案,只要简单地生成.strip()或.rstrip(),就无法再现线条,因为它们也会剥离空白。

常用文件结尾

.txt

更高级的文件写入/读取

CSV:超简单格式(读写)JSON:适合编写人类可读数据;非常常用(读写)YAML:YAML是JSON的超集,但更易于阅读(读写,JSON和YAML的比较)pickle:Python序列化格式(读写)MessagePack(Python包):更紧凑的表示(读写)HDF5(Python包):适合矩阵(读写)XML:也存在*叹息*(读写)

对于您的应用程序,以下内容可能很重要:

其他编程语言的支持读/写性能紧凑性(文件大小)

另请参阅:数据序列化格式的比较

如果您正在寻找创建配置文件的方法,您可能需要阅读我的Python配置文件短文。