如何在Python中读取文件的每一行并将每一行存储为列表中的元素?
我想逐行读取文件,并将每行附加到列表的末尾。
如何在Python中读取文件的每一行并将每一行存储为列表中的元素?
我想逐行读取文件,并将每行附加到列表的末尾。
with open(fname) 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]
with open(fname) 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]
看到 输入和输出:
with open('filename') as f:
lines = f.readlines()
或者剥离换行符:
lines = [line.rstrip('\n') for line in open('filename')]
编者注:这个答案是原始的空白剥离命令, line.strip()
正如Janus Troelsen的评论所暗示的那样,将会删除 所有领先和尾随 空白,而不仅仅是尾随 \n
。
这比必要的更明确,但是做你想要的。
with open("file.txt", "r") as ins:
array = []
for line in ins:
array.append(line)
这将从文件中生成一行“数组”。
lines = tuple(open(filename, 'r'))
如果你想要的话 \n
包括:
with open(fname) as f:
content = f.readlines()
如果你不想要 \n
包括:
with open(fname) as f:
content = f.read().splitlines()
您可以简单地执行以下操作,如建议的那样:
with open('/your/path/file') as f:
my_lines = f.readlines()
请注意,此方法有两个缺点:
1)您将所有行存储在内存中。在一般情况下,这是一个非常糟糕的主意。该文件可能非常大,您可能会耗尽内存。即使它不大,也只是浪费内存。
2)当您阅读时,这不允许处理每一行。因此,如果您在此之后处理您的行,则效率不高(需要两次通过而不是一次)。
对于一般情况,更好的方法如下:
with open('/your/path/file') as f:
for line in f:
process(line)
您可以以任何方式定义过程函数。例如:
def process(line):
if 'save the world' in line.lower():
superman.save_the_world()
(执行 Superman
课程留给你练习)。
对于任何文件大小,这都可以很好地工作,只需1遍即可完成文件。这通常是通用解析器的工作方式。
如果你不关心关闭文件,这个单线程工作:
lines = open('file.txt').read().split("\n")
该 传统 办法:
fp = open('file.txt') # Open file on read mode
lines = fp.read().split("\n") # Create a list containing all lines
fp.close() # Close file
运用 with
(推荐的):
with open('file.txt') as fp:
lines = fp.read().split("\n")
这应该封装open命令。
array = []
with open("file.txt", "r") as f:
for line in f:
array.append(line)