Why in python loop for line in file is not going through all lines after using readline before?

StackOverflow https://stackoverflow.com/questions/21181480

  •  29-09-2022
  •  | 
  •  

Pergunta

Why in python loop for line in file is not going through all lines after using readline before? How to achieve that after reading some line(s) for loop will go through all lines in file?

file = open("file.xyz", "r")
first_line = file.readline()

for line in file:
  x,y,z = line.split()
Foi útil?

Solução

Reading from a file changes the "internal pointer" to the file for the next read operation. Try:

file.seek(0)

before the for loop.

Outras dicas

To return to the start of file, use

file.seek(0)

As to why this happens: reading from a file is a bit like playing a tape, with a read head that moves along the tape. After you read a line from a file, the "read head" is now at the start of the next line. Using seek lets you "rewind" and "fast-forward" to specified points.

Reference: Python docs.

Because the file knows its position file.tell.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top