How to reload a file in python?
If I have a script that writes 1000 lines to file and then continues regular expressions against that file, however only the last 100 lines of text written will be available. One way around this is to close and reopen the file. Is there a way to reload a file after being written to or should I just make a write close open module? It may be relevant that the logfile did not exist/is empty on the first open.
>>> the_page = 'some large site opened through urllib'
>>> logfile = open('./artist/' + tags['ARTIST'], 'r+')
>>> logfile.write(the_page)
>>> print logfile.read()
Nothing appears.
>>> 'Some regular expressions search'
Searches against last 100 lines written.
>>> logfile.close()
>>> logfile = open('./artist/' 开发者_Go百科+ tags['ARTIST'], 'r+')
>>> print logfile.read()
Everything appears.
>>> 'Some regular expressions search'
Performs as expected.
This is just a hunch, but maybe a logfile.seek(0)
after the writing is finished may help. A possible explanation is given in the documentation of file.next
:
However, using
seek()
to reposition the file to an absolute position will flush the read-ahead buffer.
logfile.flush()
This should do the same thing as opening then closing the file.
As the comments point out, this is the wrong way to go about this. seek(0) is the right way.
This had quite an obvious answer, I don't need to close the file or anything, I can just open it again and it acts the same as a reload would. So:
>>> the_page = 'some large site opened through urllib'
>>> logfile = open('./artist/' + tags['ARTIST'], 'r+')
>>> logfile.write(the_page)
>>> logfile = open('./artist/' + tags['ARTIST'], 'r+')
>>> print logfile.read()
精彩评论