with open(fname) 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()
或者剥离换行符:
lines = [line.rstrip('\n') for line in open('filename')]
编者注:这个答案的原始空格剥离命令, line.strip()
,正如 Janus Troelsen 的评论所暗示的那样,将删除所有前导和尾随空格,而不仅仅是尾随\n
。
这比必要的更明确,但是做你想要的。
with open("file.txt", "r") as ins:
array = []
for line in ins:
array.append(line)