小编典典

Python-如何将文件逐行读取到列表中?

python

如何在Python中读取文件的每一行并将每一行存储为列表中的元素?
我想逐行读取文件并将每一行追加到列表的末尾。


阅读 1539

收藏
2020-02-05

共2个答案

小编典典

with open(filename) 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] 
2020-02-05
小编典典

参见输入和输出:

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

或者去掉换行符:

with open('filename') as f:
    lines = [line.rstrip() for line in f]
2020-02-05