1

Surely this has been asked before but I cannot find the question.

As I understand it, in Python (I'm using 3.3 but this is generic to both 2.x and 3.x) you cannot iterate multiple times over an open text file and that this is due to the cursor being moved to the end and does not return to the start on the next iterable loop. Therefore it does not behave like a more typical iterable.

I was wondering how to return the cursor to the start, or at least have two for loops in succession over an open file to be read.

Thanks.

AER
  • 1,549
  • 19
  • 37
  • 1
    http://stackoverflow.com/questions/2106820/re-open-files-in-python – muthan Dec 02 '14 at 23:42
  • Should I close this? Or given that upon searching for the question I was using keywords such as "iterate, open, file, python, twice" and was not returning anything. This may help people find things if they have issues with iterating files. – AER Dec 02 '14 at 23:50

1 Answers1

5

so, you're looking to rewind the file to the start again:

if your file handle is called f do it like this:

   f.seek(0)

this won't work on streams, serial ports, pipes, or network sockets: only on regular files.

user313114
  • 311
  • 1
  • 3