1

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?

Ayush
  • 909
  • 1
  • 13
  • 32

1 Answers1

4

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)
Community
  • 1
  • 1
Ben Hoyt
  • 10,694
  • 5
  • 60
  • 84