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?
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.
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.
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.
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.
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.
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