Re-open files in Python?

后端 未结 3 439
清酒与你
清酒与你 2020-12-01 13:50

Say I have this simple python script:

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

When it is run, th

相关标签:
3条回答
  • 2020-12-01 14:20

    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.

    0 讨论(0)
  • 2020-12-01 14:24

    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.

    0 讨论(0)
  • 2020-12-01 14:42

    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 讨论(0)
提交回复
热议问题