Skip to main content
 首页 » 编程设计

python之如何使用默认权限使用 Python 创建目录

2025年05月04日11Terrylee

我想使用与 shell 的 mkdir 相同的权限在 Python 中创建一个目录。

standard Python documentation说:

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.

我不想要默认的 0777 权限,而是从父目录继承的权限。我可以在不查询父目录权限的情况下执行此操作吗?

请您参考如下方法:

您已经获得了与 shell 的 mkdir 相同的权限。

带壳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.)

或者,更易读(来自 BSD 联机帮助页):

... creates the directories named as operands, in the order specified, using mode rwxrwxrwx (0777) as modified by the current umask(2).

Python 的 os.mkdir 做完全相同的事情:

... [t]he default mode is 0777... the current umask value is first masked out.

Python 实际上调用了完全相同的 POSIX mkdir shell 文档中提到的具有完全相同参数的函数。该函数定义为:

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.

或者,更易读,来自 FreeBSD/OS X 联机帮助页:

The directory path is created with the access permissions specified by mode and restricted by the umask(2) of the calling process.

如果您在 Windows 等非 POSIX 平台上,Python 会尝试模拟 POSIX 行为,即使 native shell 有一个名为 mkdir 的命令以不同方式工作。这主要是因为主要的此类 shell 是 Windows,它有一个 mkdir,它是 md 的同义词。 ,甚至没有记录它在权限方面所做工作的详细信息。