简体   繁体   English

Python 3 - 如何更改给定目录中的所有文件?

[英]Python 3 - How to chmod all files in a given directory?

In a python 3 script I'm trying to add execution permissions to all.sh files in a directory, as follows:在 python 3 脚本中,我尝试向目录中的 all.sh 文件添加执行权限,如下所示:

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

But I'm getting an error:但我收到一个错误:

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

If I run this chmod from bash, it works ok, so I guess python's chmod does not like the use of * in the path.如果我从 bash 运行这个 chmod,它工作正常,所以我猜 python 的 chmod 不喜欢在路径中使用*

What would be the correct way to chmod all.sh files in a directory then?那么在目录中 chmod all.sh 文件的正确方法是什么?

Just use a for loop.只需使用 for 循环。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM