Change ownership with os.chown()

EasyOS Module Programs · 38 of 49

Write a Python program that changes file ownership with os.chown() where the platform supports it.

Advertisement
Output
os.chown is not available on this platform

Approach

  1. os.chown exists only on Unix systems, so check for it first.

Solution

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

More os module programs

← All 49 OS Module Programs

Leave a Comment