首页 > 解决方案 > Python 3 - 如何对给定目录中的所有文件进行 chmod?

问题描述

在 python 3 脚本中,我尝试为目录中的所有 .sh 文件添加执行权限,如下所示:

from os import chmod
chmod('/path_to_dir/dir_prefix_*/bin/*.sh',0o755)

但我收到一个错误:

FileNotFoundError: [Errno 2] No such file or directory:'/path_to_dir/dir_prefix_*/bin/*.sh'

如果我从 bash 运行这个 chmod,它可以正常工作,所以我猜 python 的 chmod 不喜欢*在路径中使用。

那么在目录中对所有 .sh 文件进行 chmod 的正确方法是什么?

标签: pythonpython-3.xchmod

解决方案


只需使用 for 循环。

import os
for file in os.listdir("/mydir"):
    if file.endswith(".sh"):
        chmod(file, mode)

推荐阅读