Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-open files in Python?

Tags:

python

file

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?

like image 322
c00kiemonster Avatar asked Jan 21 '10 03:01

c00kiemonster


People also ask

How do you reopen a file in Python?

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.

How do I reopen a 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.

Can you open a file twice in Python?

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.


2 Answers

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.

like image 142
Alok Singhal Avatar answered Sep 20 '22 17:09

Alok Singhal


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.

like image 23
Smashery Avatar answered Sep 21 '22 17:09

Smashery