Re-open files in Python?

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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.

Method 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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x