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?
Opening Files in PythonPython has a built-in open() function to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly. We can specify the mode while opening a file. In mode, we specify whether we want to read r , write w or append a to the file.
Press Ctrl + Shift + F to reopen the recently closed folders. If you don't need to open the most recently closed program or folder, but another one listed on the UndoClose window, don't press the hotkeys. You can open a listed program or folder on the window by clicking it instead.
The same file can be opened more than once in the same program (or in different programs). Each instance of the open file has its own file pointer that can be manipulated independently.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With