如何在Python中读取文件的每一行,并将每一行存储为列表中的元素?
我想逐行读取文件,并将每一行附加到列表的末尾。
如何在Python中读取文件的每一行,并将每一行存储为列表中的元素?
我想逐行读取文件,并将每一行附加到列表的末尾。
当前回答
这段代码将把整个文件读入内存,并删除每行末尾的所有空白字符(换行符和空格):
with open(filename) as file:
lines = [line.rstrip() for line in file]
如果您正在处理一个大文件,那么您应该逐行读取并处理它:
with open(filename) as file:
for line in file:
print(line.rstrip())
在Python 3.8及以上版本中,可以使用while循环和walrus运算符,如下所示:
with open(filename) as file:
while (line := file.readline().rstrip()):
print(line)
根据您计划对文件执行的操作以及文件的编码方式,您可能还需要手动设置访问模式和字符编码:
with open(filename, 'r', encoding='UTF-8') as file:
while (line := file.readline().rstrip()):
print(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']
如果要包含以下内容:
with open(fname) as f:
content = f.readlines()
如果不希望包含:
with open(fname) as f:
content = f.read().splitlines()
下面是我用来简化文件I/O的Python(3)助手库类:
import os
# handle files using a callback method, prevents repetition
def _FileIO__file_handler(file_path, mode, callback = lambda f: None):
f = open(file_path, mode)
try:
return callback(f)
except Exception as e:
raise IOError("Failed to %s file" % ["write to", "read from"][mode.lower() in "r rb r+".split(" ")])
finally:
f.close()
class FileIO:
# return the contents of a file
def read(file_path, mode = "r"):
return __file_handler(file_path, mode, lambda rf: rf.read())
# get the lines of a file
def lines(file_path, mode = "r", filter_fn = lambda line: len(line) > 0):
return [line for line in FileIO.read(file_path, mode).strip().split("\n") if filter_fn(line)]
# create or update a file (NOTE: can also be used to replace a file's original content)
def write(file_path, new_content, mode = "w"):
return __file_handler(file_path, mode, lambda wf: wf.write(new_content))
# delete a file (if it exists)
def delete(file_path):
return os.remove() if os.path.isfile(file_path) else None
然后使用FileIO.lines函数,如下所示:
file_ext_lines = FileIO.lines("./path/to/file.ext"):
for i, line in enumerate(file_ext_lines):
print("Line {}: {}".format(i + 1, line))
请记住,mode(默认为“r”)和filter_fn(默认为检查空行)参数是可选的。
您甚至可以删除read、write和delete方法,只保留FileIO.line,甚至将其转换为一个单独的方法read_lines。
我喜欢使用以下内容。立即阅读台词。
contents = []
for line in open(filepath, 'r').readlines():
contents.append(line.strip())
或者使用列表理解:
contents = [line.strip() for line in open(filepath, 'r').readlines()]
这段代码将把整个文件读入内存,并删除每行末尾的所有空白字符(换行符和空格):
with open(filename) as file:
lines = [line.rstrip() for line in file]
如果您正在处理一个大文件,那么您应该逐行读取并处理它:
with open(filename) as file:
for line in file:
print(line.rstrip())
在Python 3.8及以上版本中,可以使用while循环和walrus运算符,如下所示:
with open(filename) as file:
while (line := file.readline().rstrip()):
print(line)
根据您计划对文件执行的操作以及文件的编码方式,您可能还需要手动设置访问模式和字符编码:
with open(filename, 'r', encoding='UTF-8') as file:
while (line := file.readline().rstrip()):
print(line)