我有一个名为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()
逐行打印文件内容。建议采用后者,因为你不需要一次性将整个文件内容加载到内存中。