如何在Python中读取文件的每一行并将每一行存储为列表中的元素? 我想逐行读取文件并将每一行追加到列表的末尾。
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]