如何在Python中读取文件的每一行,并将每一行存储为列表中的元素?
我想逐行读取文件,并将每一行附加到列表的末尾。
如何在Python中读取文件的每一行,并将每一行存储为列表中的元素?
我想逐行读取文件,并将每一行附加到列表的末尾。
当前回答
您也可以在NumPy中使用loadtxt命令。这比genfromttxt检查的条件更少,因此可能更快。
import numpy
data = numpy.loadtxt(filename, delimiter="\n")
其他回答
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(fname) as f:
content = f.readlines()
如果不希望包含:
with open(fname) as f:
content = f.read().splitlines()
这里还有一个选项,对文件使用列表理解;
lines = [line.rstrip() for line in open('file.txt')]
这应该是更有效的方法,因为大部分工作都是在Python解释器内完成的。
具有文本文件内容:
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']