开发者

Re-open files in Python?

开发者 https://www.devze.com 2022-12-17 09:52 出处:网络
Say I have this simple python script: file = open(\'C:\\\\some_text.txt\') print file.readlines() print file.readli开发者_C百科nes()

Say I have this simple python script:

file = open('C:\\some_text.txt')
print file.readlines()
print file.readli开发者_C百科nes()

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?


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.


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号