Low level file descriptors and high-level Python files

Steven D'Aprano steve at pearwood.info
Tue Sep 1 16:57:22 CEST 2015


Let's suppose somebody passes me a file descriptor to work with. It could
come from somewhere else, but for the sake of discussion let's pretend I
create it myself this way:

import os
fd = os.open("some path", "w")


I then turn it into a file object:

file_obj = os.fdopen(fd, mode)


Q1:  In this example, I know that I opened the fd in write mode, because I
did it myself. But since I'm not actually opening it, how do I know what
mode to use in the call to fdopen? Is there something I can call to find
out what mode a file descriptor has been opened with?


Now let's suppose I solve that problem, process the file_obj, and close it:

file_obj.close()

Q2:  Do I still have to close the file descriptor with os.close(fd)? 
(I think not.)


Q3:  I could probably answer Q2 myself if I knew how to check whether a fd
was open or not. With a file object, I can inspect file_obj.closed and it
will tell me whether the file is open or not. Is there an equivalent for
file descriptors?



-- 
Steven



More information about the Python-list mailing list