How to Use chmod in Python?

Python Tutorials

The chmod command stands for “change mode”. In Unix and Unix-like operating systems, it is used to change the access permissions of files.

In Python, you can easily change the permission of files using the os.chmod() method.

Use os.chmod() to Change Files Permission

Call the os.chmod(file, permission) method to change the existing permission of file to the specified permission. The permission should be an octal number i.e. prefixed with 0o.

import os
file = 'myfile.txt'
os.chmod(file, 0o775)

To check the permission of the file, use the os.stat(file) to get the status of the file and access the st_mode on the result.

status = os.stat(file)
print(status.st_mode[-3:])
# 775

Leave a Reply

Your email address will not be published. Required fields are marked *