1

I have a simple question which I stock in it !

for line1 in file: print(line1) for line2 in file: print(line2) for line3 in file: print(line3)

I expect this to work three times, but only "for line1 in file:" work.

A newbie
  • 17
  • 4
  • For a simple fix, add `file.seek(0)` in between every `for` loop. – iz_ Jan 08 '19 at 03:17
  • 1
    @Tomothy32: Unless `file` is backed by a transient thing (pipe, socket, etc.). In which case you only get one shot at it, and must either slurp to memory (e.g. as a `list`) if you trust you'll have enough memory, or copy to a temp file which you then reread with `seek`s. – ShadowRanger Jan 08 '19 at 03:24
  • Better duplicate: [Iterating on a file using Python](https://stackoverflow.com/questions/10255273/iterating-on-a-file-using-python) – Kevin Ji Jan 08 '19 at 03:58

1 Answers1

1

Because the file is read as part of iterating over the lines. You'll need to reopen the file each time, or read the whole file into a list of lines (via file.readlines() perhaps) and iterate over that, if memory limits permit. Any open file has a "read pointer" that tracks what's been read, which advances with each line consumed. The loops as written will each consume the whole file.

stolenmoment
  • 443
  • 3
  • 6
  • "You'll need to reopen the file each time, or read the whole file into a list of lines (via file.readlines() perhaps) and iterate over that" - or, as @Tomothy32 says, "be kind, rewind". – Amadan Jan 08 '19 at 04:08