I'm making a temporary file with tempfile.mkstemp()
. It returns an os-level fd along with the path to the file. I want to os.fdopen()
the os-level file descriptor to write to it. If I then close the file that os.fdopen()
returned, will the os-level file descriptor be closed, or do I have to os.close()
it explicitly? The docs don't seem to say what happens explicitly.
If fdopen() returns NULL, use close() to close the file. If fdopen() is successful, you must use fclose() to close the stream and file.
fdopen() takes an existing file descriptor and builds a Python file object around it. It converts a file descriptor to a full file object. It is useful when interfacing with C code or with APIs that only create low-level file descriptors.
close() method in Python is used to close the given file descriptor, so that it no longer refers to any file or other resource and may be reused. A file descriptor is small integer value that corresponds to a file or other input/output resource, such as a pipe or network socket.
fd − This is the file descriptor for which a file object is to be returned. mode − This optional argument is a string indicating how the file is to be opened. The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending.
I'm pretty sure the fd will be closed. If you don't want that you can dup it first. Of course you can always test this easily enough.
Test is like this:
from __future__ import print_function
import os
import tempfile
import errno
fd, tmpname = tempfile.mkstemp()
fo = os.fdopen(fd, "w")
fo.write("something\n")
fo.close()
try:
os.close(fd)
except OSError as oserr:
if oserr.args[0] == errno.EBADF:
print ("Closing file has closed file descriptor.")
else:
print ("Some other error:", oserr)
else:
print ("File descriptor not closed.")
Which shows that the underlying file descriptor is closed when the file object is 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