我想把整个文件读入Python列表中,有人知道怎么做吗?
更简单:
with open(path) as f:
myList = list(f)
list(f.read().splitlines())
。这将把文件内容读入一个列表中,并去除每行末尾的换行符。print "\nReading the entire file into a list."
text_file = open("read_it.txt", "r")
lines = text_file.readlines()
print lines
print len(lines)
for line in lines:
print line
text_file.close()
Max的回答是可行的,但每行末尾会留下换行符(\n
)。
除非这是期望的行为,否则请使用以下范例:
with open(filepath) as f:
lines = f.read().splitlines()
for line in lines:
print line # Won't have '\n' at the end
或者:
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)
pathlib
允许您使用read_text方法安全地在一行中读取整个文件,而无需编写with open(...)
语句 - 它将为您打开文件、读取内容并关闭文件:lines = Path(path_to_file).read_text().splitlines()
另一种略有不同的方式:
with open(filename) as f:
lines = f.readlines()
for line in lines:
print(line.rstrip())