gpt4 book ai didi

python - 更改新目录和文件的权限模式

转载 作者:太空宇宙 更新时间:2023-11-04 12:05:34 26 4
gpt4 key购买 nike

在 python 2.7 中,我将数据保存到一个路径,例如A/B/C/data.txt:

import os

file_path = 'A/B/C/data.txt'

# create directory A/B/C
dir_name = os.path.dirname(file_path)
if not os.path.exists(dir_name):
os.makedirs(dirp_name)

# save data to file
with open(file_path, 'w') as f:
json.dump(data, f)

# change file permission mode to be 0x666
os.chmod(file_path, 0666)

文件 data.txt 的权限模式已更改。但是,此代码不会更改路径上目录 A/B/C 的权限模式。我也想设置目录的权限模式。

os.chmod('A', 0666)
os.chmod('A/B', 0666)
os.chmod('A/B/C', 0666)

有没有一种优雅的方式来做到这一点?

谢谢!

最佳答案

os.mkdir(path[, mode]) 允许我们在创建目录时设置权限模式。默认模式是 0777(八进制)。如果该目录已经存在,则会引发 OSError。

解决方案一:

# RW only permission mode is 0666 in python 2 and 0o666 in python 3
RW_only = 0666

# create directory A/B/C
dir_name = os.path.dirname(file_path)

if not os.path.exists(dir_name):
os.makedirs(dirp_name, RW_only)

# save data to file
with open(file_path, 'w') as f:
json.dump(data, f)

# change file permission mode to be 0x666
os.chmod(file_path, RW_only)

但是,从python 3.7开始,mode参数不再影响新建的中级目录的文件权限位,所以方案一只适用于旧版本。

这就是我最终得到的结果:使用进程 umask

解决方案 2 [更好]:

# mkdirs has mode 0777 by default, we get 0666 by masking out 0111
old_umask = os.umask(0111)

# create directory A/B/C
dir_name = os.path.dirname(file_path)

if not os.path.exists(dir_name):
os.makedirs(dirp_name)

# save data to file (file mode is 0666 by default)
with open(file_path, 'w') as f:
json.dump(data, f)

# restore old_umask
os.umask(old_umask)

关于python - 更改新目录和文件的权限模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50848968/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com