Computer >> Computer tutorials >  >> Programming >> Python

How to change file permissions in Python?


To change the permission of a file, you can use the os.chmod(file, mode) call. Note that the mode should be specified in octal representation and therefore must begin with a 0o. For example, to make a file readonly, you can set the permission to 0o777, you can use:

>>> import os
>>> os.chmod('my_file', 0o777)

You can also use flags from the stat module. You can read more about these flags here: https://docs.python.org/2/library/stat.html

Another way to acheive it is using a subprocess call:

>>> import subprocess
>>> subprocess.call(['chmod', '0444', 'my_file'])