14

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.

1 Answer 1

10

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.