Miro
Miro

Reputation: 609

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

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()

Upvotes: 1

Views: 349

Answers (3)

jonrsharpe
jonrsharpe

Reputation: 122133

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.

Upvotes: 2

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

file.seek(0)

before the for loop.

Upvotes: 3

User
User

Reputation: 14883

Because the file knows its position file.tell.

Upvotes: 1

Related Questions