如何将文件逐行读入列表? [英] How to read a file line-by-line into a list?
问题描述
如何在 Python 中读取文件的每一行并将每一行作为元素存储在列表中?
How do I read every line of a file in Python and store each line as an element in a list?
我想逐行读取文件并将每一行附加到列表的末尾.
I want to read the file line by line and append each line to the end of the list.
推荐答案
此代码会将整个文件读入内存并从每行末尾删除所有空白字符(换行符和空格):
This code will read the entire file into memory and remove all whitespace characters (newlines and spaces) from the end of each line:
with open(filename) as file:
lines = file.readlines()
lines = [line.rstrip() for line in lines]
如果您正在处理一个大文件,那么您应该逐行读取和处理它:
If you're working with a large file, then you should instead read and process it line-by-line:
with open(filename) as file:
for line in file:
print(line.rstrip())
在 Python 3.8 及更高版本中,您可以使用带有 walrus 的 while 循环运算符像这样:
In Python 3.8 and up you can use a while loop with the walrus operator like so:
with open(filename) as file:
while (line := file.readline().rstrip()):
print(line)
根据您打算对文件做什么以及它是如何编码的,您可能还想手动设置 访问模式和字符编码:
Depending on what you plan to do with your file and how it was encoded, you may also want to manually set the access mode and character encoding:
with open(filename, 'r', encoding='UTF-8') as file:
while (line := file.readline().rstrip()):
print(line)
这篇关于如何将文件逐行读入列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!