Yes, this is supported by passing the dir_fd
argument to various functions in the standard os
module. See for example os.open()
:
Open the file path and set various flags [...]
This function can support paths relative to directory descriptors with the dir_fd parameter.
If you want to use high-level file objects such as those returned by the builtin open()
function, that function's documentation provides example code showing how to do this using the opener
parameter to that function. Note that open()
and os.open()
are entirely different functions and should not be confused. Alternatively, you could open the file with os.open()
and then pass the file descriptor number to os.fdopen()
or to open()
.
It should also be noted that this currently only works on Unix; the portable and future-proof way to check for dir_fd
support is to write code such as the following:
if os.open in os.supports_dir_fd:
# Use dir_fd.
else:
# Don't.
On the other hand, I'm not entirely sure Windows even allows opening a directory in the first place. You certainly can't do it with _open()
/_wopen()
, which are documented to fail if "the given path is a directory." To be safe, I recommend only trying to open the directory after you check for dir_fd
support.