I have a file called test which has the contents:
a
b
c
d
e
f
g
I am using the following python code to read this file line by line and print it out:
with open('test.txt') as x:
for line in x:
print(x.read())
The result of this is to print out the contents of the text file except for the first line, i.e. the result is:
b
c
d
e
f
g
Does anyone have any idea why it might be missing the first line of the file?
解决方案
Because for line in x iterates through every line.
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
Perhaps you meant:
with open('test.txt') as x:
print(x.read())
to print it all at once, or:
with open('test.txt') as x:
for line in x:
print line.rstrip()
to print it line by line. The latter is recommended since you don't need to load the whole contents of the file into memory at once.