drevicko
drevicko

Reputation: 15200

How to get a file descriptor for a folder in python

Many os methods allow you to specify the file descriptor dir_fd of a folder and provide a file path relative to that folder. The example I stumbled on is os.symlink(source_path, target_path, *, dir_fd=None), where I wanted the symlink to be relative. Without providing dir_fd, my symlink appears with an absolute path or relative to the cwd.

How do I obtain such a file descriptor? I cannot use the builtin open() on a directory (else I could get a file descriptor from the resulting file object).

Upvotes: 7

Views: 3765

Answers (1)

drevicko
drevicko

Reputation: 15200

I found an answer in this blog. Adding it here for prosperity:

import os
fd  = os.open( "/tmp", os.O_RDONLY )
print( fd )

Upvotes: 9

Related Questions