Ayush Ayush - 1 year ago 113
Bash Question

How to change permissions of multiple files using os.chmod

I have a directory which contains multiple files (some shell ending with .sh, some text files and some python files ending with .py extension).

I want to add execute permission to all shell files (ending with .sh) using os.chmod command. Basically I want to do this:

chmod +x *.sh

I tried checking for permissions first by doing this:

>>> s = os.stat('*.ksh')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory: '*.ksh'

But it won't work.
How can I do this in pythonic way?

Answer Source

Use the glob module to get a list of files, and then loop over them:

import glob, os, stat

for name in glob.glob('*.sh'):
    print(name, os.stat(name))

And you can use os.chmod() as per this question to actually add the executable mode bit:

for name in glob.glob('*.sh'):
    st = os.stat(name)
    os.chmod(name, st.st_mode | stat.S_IEXEC)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download