Reading from text file with python - first line skipped

I have a file called test that contains the contents:

a b c d e f g 

I use 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 is to print the contents of the text file except for the first line, i.e. the result:

 b c d e f g 

Does anyone know why the first line of a file might be missing?

+4
source share
1 answer

Because for line in x iterates through each 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 

Did you mean:

 with open('test.txt') as x: print(x.read()) 

to print all at once, or:

 with open('test.txt') as x: for line in x: print line.rstrip() 

for printing line by line. The latter is recommended, since you do not need to immediately load the entire contents of the file into memory.

+8
source

Source: https://habr.com/ru/post/1487485/


All Articles