1

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

3 Answers 3

3

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

file.seek(0)

before the for loop.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

Because the file knows its position file.tell.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.