does closing a file opened with os.fdopen close the os-level fd?
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 t开发者_开发百科hen 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.
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.
精彩评论