我有一个名为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
有没有人知道为什么它可能会丢失文件的第一行?
答案 0 :(得分:8)
因为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()
逐行打印。建议使用后者,因为您不需要立即将文件的全部内容加载到内存中。