Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can I do with a closed file object?

Tags:

python

file

When you open a file, it's stored in an open file object which gives you access to various methods on it such as reading or writing.

>>> f = open("file0")
>>> f
<open file 'file0', mode 'r' at 0x0000000002E51660>

Of course when you're done you should close your file to prevent it taking up memory space.

>>> f.close()
>>> f
<closed file 'file0', mode 'r' at 0x0000000002E51660>

This leaves a closed file, so that the object still exists though it's no longer using space for the sake of being readable. But is there any practical application of this? It can't be read, or written. It can't be used to reopen the file again.

>>> f.open()

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    f.open()
AttributeError: 'file' object has no attribute 'open'

>>> open(f)

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    open(f)
TypeError: coercing to Unicode: need string or buffer, file found

Is there a practical use for this closed file object aside from identifying that a file object is being referenced but is closed?

like image 435
SuperBiasedMan Avatar asked May 21 '15 16:05

SuperBiasedMan


People also ask

How do I open a closed file?

To recover and reopen an accidentally closed window, right-click on the icon and select the file you wish to reopen. To recover all, simply double-click on the icon. Features: Click the X or press Alt-F4 to close an application.

What happens if you try to read from a closed file Python?

If you try to access a closed file, you will raise the ValueError: I/O operation on closed file. I/O means Input/Output and refers to the read and write operations in Python. To solve this error, ensure you put all writing operations before closing the file.

Why it is important to close a file and how do you close it?

Because files are limited resources managed by the operating system, making sure files are closed after use will protect against hard-to-debug issues like running out of file handles or experiencing corrupted data.

What are closed files?

n. A file containing records generated by a process that has been completed and to which additional information is not likely to be added; a cut-off file.


1 Answers

One use is using the name to reopen the file:

open(f.name).read()

I use the name attribute when changing a file content using a NamedTemporaryFile to write the updated content to then replace the original file with shutil.move:

with open("foo.txt") as f, NamedTemporaryFile("w", dir=".", delete=False) as temp:
    for line in f:
        if stuff:
            temp.write("stuff")

shutil.move(temp.name, "foo.txt")

Also as commented you can use the f.closed to see if the file is really closed.

like image 70
Padraic Cunningham Avatar answered Oct 02 '22 23:10

Padraic Cunningham