41

Say I have this simple python script:

file = open('C:\\some_text.txt')
print file.readlines()
print file.readlines()

When it is run, the first print prints a list containing the text of the file, while the second print prints a blank list. Not completely unexpected I guess. But is there a way to 'wind back' the file so that I can read it again? Or is the fastest way just to re-open it?

4
  • 1
    You could try file.close() and open vs. file.seek and report back on what you learned. Then we could comment on your results. Commented Jan 21, 2010 at 3:59
  • 1
    Hey c00kiemonster! If Alok's response answers your question, please press the tick to the left of his answer. This marks it as "the right answer" so other people in the future will know that it works. Plus it gives you extra reputation points :-) Commented Jan 21, 2010 at 4:05
  • 1
    I ran a quick test on a 170k file, and it was pretty much the same time, a few milliseconds each. Commented Jan 21, 2010 at 4:12
  • So there is no "fastest"? Is that the bottom line? Commented Jan 21, 2010 at 12:46

3 Answers 3

86

You can reset the file pointer by calling seek():

file.seek(0)

will do it. You need that line after your first readlines(). Note that file has to support random access for the above to work.

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

4 Comments

Awesome. Reminds me of the good old peek and poke stuff with the venerable C64!
I think it's standard POSIX interface.
@Stefano: I think you're right. seek() of file objects in Python is most likely a thin wrapper around fseek() or similar.
It is precisely the OS call. Nothing to do with Basic PEEK and POKE. Nothing.
3

For small files, it's probably much faster to just keep the file's contents in memory

file = open('C:\\some_text.txt')
fileContents = file.readlines()
print fileContents
print fileContents # This line will work as well.

Of course, if it's a big file, this could put strain on your RAM.

Comments

3

Remember that you can always use the with statement to open and close files:

from __future__ import with_statement

with open('C:\\some_text.txt') as file:
    data = file.readlines()
#File is now closed
for line in data:
    print line

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.