How to get the owner and group of a folder with Python on a Linux machine?

dan picture dan · May 29, 2009 · Viewed 23.9k times · Source

How can I get the owner and group IDs of a directory using Python under Linux?

Answer

Ayman Hourieh picture Ayman Hourieh · May 29, 2009

Use os.stat() to get the uid and gid of the file. Then, use pwd.getpwuid() and grp.getgrgid() to get the user and group names respectively.

import grp
import pwd
import os

stat_info = os.stat('/path')
uid = stat_info.st_uid
gid = stat_info.st_gid
print uid, gid

user = pwd.getpwuid(uid)[0]
group = grp.getgrgid(gid)[0]
print user, group