我有一个名为 test 的文件,其中包含以下内容:
a
b
c
d
e
f
g
我正在使用以下 python 代码逐行读取此文件并将其打印出来:
with open('test.txt') as x:
for line in x:
print(x.read())
这样做的结果是打印出文本文件除了第一行以外的内容,即结果是:
b
c
d
e
f
g
有谁知道为什么它可能会丢失文件的第一行?
因为for line in x
遍历每一行。
with open('test.txt') as x:
for line in x:
# By this point, line is set to the first line
# the file cursor has advanced just past the first line
print(x.read())
# the above prints everything after the first line
# file cursor reaches EOF, no more lines to iterate in for loop
也许你的意思是:
with open('test.txt') as x:
print(x.read())
一次打印,或者:
with open('test.txt') as x:
for line in x:
print line.rstrip()
逐行打印。建议使用后者,因为您不需要一次将文件的全部内容加载到内存中。