Change permissions with os.chmod()

EasyOS Module Programs · 37 of 49

Write a Python program to change a file’s permissions with os.chmod().

Advertisement
Output
writable: False
writable: True

Approach

  1. Make the file read-only, check it, then make it writable again.

Solution

Python
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.

More os module programs

← All 49 OS Module Programs

Leave a Comment