我有嵌套目录路径,我正在使用以下代码逐部分更改其权限。假设路径为“/apps/sys/utils/prod/sales/apparel/”。
我可以一次性更改其权限,而不是在循环中逐部分执行以获得相同的效果/结果吗?
import os
import stat
def change_permissions(path, new_mode):
"""Change permissions of the directory to new_mode."""
if not os.path.islink(path):
original_mode = os.stat(path).st_mode
os.chmod(path, new_mode)
oct_perm = oct(new_mode)
unix_perm = oct_perm[-3: (len(oct_perm))]
print(f"Permission of {path} changed to {new_mode} = {unix_perm}")
return original_mode
return None
target_full_path = "/apps/sys/utils/prod/sales/apparel/shirts.csv"
# Determine the directory path up to which permissions need to be changed
target_dir = os.path.dirname(target_full_path)
print(f"The abstract file dir path upto which perm to be changed {target_dir}")
# Change permissions for the specific directory needed
original_permissions = []
current_dir = "/apps/sys/utils/prod"
for part in target_dir.split(os.sep)[len(dest_root.split(os.sep)):]:
current_dir = os.path.join(current_dir, part)
print(f"\n### part = {part} and current_dir = {current_dir}")
if not os.path.exists(current_dir):
os.makedirs(current_dir)
print(f"Created the current_dir = {current_dir}")
original_mode = change_permissions(current_dir, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
original_permissions.append((current_dir, original_mode))
print (f"Original mode for current_dir ({current_dir}) is {original_mode}\n")
如果我理解正确的话,您想要更改树路径上每个单独目录的权限,如果不存在则预先创建每个目录。
我认为没有一个函数可以做到这一点,而且除了更改路径的每个目录之外,我不知道还有其他方法。这意味着在循环中。
除非您接受:
依赖操作系统命令
还更改目录文件权限
然后您可以在最顶层目录上发出“chmod -R”shell 命令。
什么是
dest_root
“?不应该是吗current_dir
?如果只需要创建一个具有给定权限的目录树,则使用os.makedirs作为模式参数。