Python Practice › OS Module Programs › Program 38
Change ownership with os.chown()
Write a Python program that changes file ownership with os.chown() where the platform supports it.
Output
os.chown is not available on this platform
Approach
os.chownexists only on Unix systems, so check for it first.
Solution
import os open("owned.txt", "w").close()if hasattr(os, "chown"): st = os.stat("owned.txt") os.chown("owned.txt", st.st_uid, st.st_gid) # same owner: allowed without root print("ownership set")else: print("os.chown is not available on this platform")Output
os.chown is not available on this platform
Line by line
Line 5
Changing to a different owner usually needs administrator rights; re-applying the current owner shows the call safely.
Learn the concept
New to this topic? Read the lesson, then come back.