Python-如何将文件逐行读取到列表中?
发布于 2021-02-02 23:24:40
如何在Python中读取文件的每一行并将每一行存储为列表中的元素?
我想逐行读取文件并将每一行追加到列表的末尾。
关注者
0
被浏览
346
1 个回答
-
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]
-
参见输入和输出:
with open('filename') as f: lines = f.readlines()
或者去掉换行符:
with open('filename') as f: lines = [line.rstrip() for line in f]