在Python中使用os.makedirs创建目录时的权限问题

gre*_*n69 40 python


我只是试图处理上传的文件并将其写入工作目录,其名称是系统时间戳.问题是我想用完全权限创建该目录(777)但我不能!使用以下代码片段,创建的目录具有755个权限.

def handle_uploaded_file(upfile, cTimeStamp):
    target_dir = "path_to_my_working_dir/tmp_files/%s" % (cTimeStamp)
    os.makedirs(target_dir, mode=0777)
Run Code Online (Sandbox Code Playgroud)

有人可以帮帮我吗?非常感谢.

srg*_*erg 36

根据官方python 文档,os.makedirs在某些系统上可能会忽略该函数的mode参数,并且在不被忽略的系统上,当前的umask值被屏蔽掉.

无论哪种方式,您都可以使用该os.chmod功能强制模式为0o777(0777引发语法错误).

  • +1:`umask`通常是出现意外权限时的罪魁祸首. (11认同)

dbn*_*dbn 30

您遇到了问题,因为os.makedir()尊重当前进程的umask(请参阅此处的文档).如果要忽略umask,则必须执行以下操作:

import os
try:
    original_umask = os.umask(0)
    os.makedirs('full/path/to/new/directory', desired_permission)
finally:
    os.umask(original_umask)
Run Code Online (Sandbox Code Playgroud)

在你的情况,你要desired_permission成为0777(八进制,而不是字符串).大多数其他用户可能想要0755或0770.

  • “original_umask = os.umask(0)”行不应该在 try 块之外(就在之前)吗?否则,如果它引发,“finally”块可能会产生意想不到的结果。 (3认同)
  • 对于 py3 环境,0XYZ(八进制数字)必须写为 0oXYZ。 (3认同)
  • 稍作修正:umask 不是文件或目录的属性,它是由正在运行的进程设置的。通常umask是从shell继承的。 (2认同)

use*_*286 13

对于Unix系统(当模式未被忽略时),首先使用当前用户的umask屏蔽提供的模式.您还可以修复运行此代码的用户的umask.那你就不用打电话了os.chmod().请注意,如果您不修复umask并使用os.makedirs方法创建多个目录,则必须标识已创建的文件夹并对其应用os.chmod.

对我来说,我创建了以下功能:

def supermakedirs(path, mode):
    if not path or os.path.exists(path):
        return []
    (head, tail) = os.path.split(path)
    res = supermakedirs(head, mode)
    os.mkdir(path)
    os.chmod(path, mode)
    res += [path]
    return res
Run Code Online (Sandbox Code Playgroud)


veb*_*ben 6

其他答案对我不起作用(使用 python 2.7)。

我之前必须添加os.umask(0),以删除当前用户的掩码。我必须将模式从更改07770o777

def handle_uploaded_file(upfile, cTimeStamp):
    target_dir = "path_to_my_working_dir/tmp_files/%s" % (cTimeStamp)
    os.umask(0)
    os.makedirs(path, mode=0o777)
Run Code Online (Sandbox Code Playgroud)