Reputation: 127498
I want to create a directory in Python using the same permissions as I'd get with the shell's mkdir
.
The standard Python documentation says:
os.mkdir(path[, mode])
Create a directory named path with numeric mode mode. The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out. If the directory already exists, OSError is raised.
I don't want the default 0777
permissions, but rather the permissions inherited from the parent directory. Can I do that without querying the parent directory's permissions?
Upvotes: 2
Views: 5117
Reputation: 365815
You already are getting the same permissions you'd get with the shell's mkdir
.
With the shell mkdir:
For each dir operand, the mkdir utility shall perform actions equivalent to the mkdir() function defined in the System Interfaces volume of IEEE Std 1003.1-2001, called with the following arguments:
The dir operand is used as the path argument.
The value of the bitwise-inclusive OR of S_IRWXU, S_IRWXG, and S_IRWXO is used as the mode argument. (If the -m option is specified, the mode option-argument overrides this default.)
Or, more readably (from the BSD manpage):
... creates the directories named as operands, in the order specified, using mode rwxrwxrwx (0777) as modified by the current umask(2).
Python's os.mkdir
does the exact same thing:
... [t]he default mode is 0777... the current umask value is first masked out.
Python in fact calls the exact same POSIX mkdir function mentioned in the shell documentation with the exact same arguments. That function is defined as:
The file permission bits of the new directory shall be initialized from mode. These file permission bits of the mode argument shall be modified by the process' file creation mask.
Or, more readably, from the FreeBSD/OS X manpage:
The directory path is created with the access permissions specified by mode and restricted by the umask(2) of the calling process.
If you're on a non-POSIX platform like Windows, Python tries to emulate POSIX behavior, even if the native shell has a command called mkdir
that works differently. Mainly this is because the primary such shell is Windows, which has an mkdir
that's a synonym for md, and the details of what it does as far as permissions aren't even documented.
Upvotes: 7
Reputation: 55962
It looks like you might be able to get the current permissions of the directory you are writing the file to using How can I get a file's permission mask? and then pass that mode to mkdir
?
Upvotes: 3