7

I'm trying to read lines of some files multiple times in Python.

I'm using this basic way :

 with open(name, 'r+') as file:
                for line in file:
                    # Do Something with line

And that's working fine, but if I want to iterate a second time each lines while I'm still with my file open like :

 with open(name, 'r+') as file:
                for line in file:
                    # Do Something with line
                for line in file:
                    # Do Something with line, second time

Then it doesn't work and I need to open, then close, then open again my file to make it work.

with open(name, 'r+') as file:
                    for line in file:
                        # Do Something with line
with open(name, 'r+') as file:
                    for line in file:
                        # Do Something with line

Thanks for answers !

Retsim
  • 433
  • 1
  • 5
  • 19

1 Answers1

23

Use file.seek() to jump to a specific position in a file. However, think about whether it is really necessary to go through the file again. Maybe there is a better option.

with open(name, 'r+') as file:
    for line in file:
        # Do Something with line
    file.seek(0)
    for line in file:
        # Do Something with line, second time
Tim Zimmermann
  • 6,132
  • 3
  • 30
  • 36
  • Thanks that's working fine ! For now we need to to through the entire file multiple times because we use values from the first iteration to be able to do the second one, that's a little tricky but we also made a better version wich iterate only once, but I wanted to have this for debuging purposes, files we actually iterate trough are not using same structure, it's pretty random, value we need to get first to iterate properly is never at the same line number, we can't use a linecache or islice then. – Retsim Oct 10 '14 at 08:52