Use permission symbols instead of numbers
Your problem would have been avoided if you had used the more semantically named permission symbols rather than raw magic numbers, e.g. for 664
:
#!/usr/bin/env python3
import os
import stat
os.chmod(
'myfile',
stat.S_IRUSR |
stat.S_IWUSR |
stat.S_IRGRP |
stat.S_IWGRP |
stat.S_IROTH
)
This is documented at https://docs.python.org/3/library/os.html#os.chmod and the names are the same as the POSIX C API values documented at man 2 stat
.
Another advantage is the greater portability as mentioned in the docs:
Note: Although Windows supports
chmod()
, you can only set the file’s read-only flag with it (via thestat.S_IWRITE
andstat.S_IREAD
constants or a corresponding integer value). All other bits are ignored.
chmod +x
is demonstrated at: How do you do a simple "chmod +x" from within python?
Tested in Ubuntu 16.04, Python 3.5.2.