我只是试图处理上传的文件并将其写入工作目录,其名称是系统时间戳.问题是我想用完全权限创建该目录(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)
有人可以帮帮我吗?非常感谢.
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.
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)
其他答案对我不起作用(使用 python 2.7)。
我之前必须添加os.umask(0),以删除当前用户的掩码。我必须将模式从更改0777为0o777:
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)