我想将整个文件读入任何人都知道如何的python列表中?
答案 0 :(得分:6)
简单:
with open(path) as f:
myList = list(f)
如果您不想要换行,可以执行list(f.read().splitlines())
答案 1 :(得分:3)
答案 2 :(得分:1)
Max的答案会有效,但您会在每行末尾留下endline
字符(\n
)。
除非这是理想的行为,否则请使用以下范例:
with open(filepath) as f:
lines = f.read().splitlines()
for line in lines:
print line # Won't have '\n' at the end
答案 3 :(得分:0)
或者:
allRows = [] # in case you need to store it
with open(filename, 'r') as f:
for row in f:
# do something with row
# And / Or
allRows.append(row)
请注意,此处不需要关心关闭文件,也不需要在此处使用readlines。
答案 4 :(得分:0)
请注意,Python3的pathlib
允许您使用read_text method安全地在一行中读取整个文件,而无需编写with open(...)
语句 - 它将打开文件,阅读内容并为您关闭文件:
lines = Path(path_to_file).read_text().splitlines()
答案 5 :(得分:0)
另一种方式,稍有不同:
with open(filename) as f:
lines = f.readlines()
for line in lines:
print(line.rstrip())