Python Practice › OS Module Programs › Program 37
Change permissions with os.chmod()
Write a Python program to change a file’s permissions with os.chmod().
Output
writable: False writable: True
Approach
- Make the file read-only, check it, then make it writable again.
Solution
import osimport stat open("locked.txt", "w").close()os.chmod("locked.txt", stat.S_IREAD)print("writable:", os.access("locked.txt", os.W_OK))os.chmod("locked.txt", stat.S_IREAD | stat.S_IWRITE)print("writable:", os.access("locked.txt", os.W_OK))Output
writable: False writable: True
Note
On Windows, chmod can only switch the read-only flag; on Linux and macOS it controls full owner, group and other permissions such as 0o755.
Learn the concept
New to this topic? Read the lesson, then come back.