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

Each Answer to this Q is separated by one/two green lines.

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

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

Since Python 3.4.4, the Path class of pathlib module provides a nice syntax for this:

from pathlib import Path
whatever = Path("relative/or/absolute/path/to_whatever")
if whatever.exists():
    print("Owner: %s" % whatever.owner())
    print("Group: %s" %

Use os.stat:

>>> s = os.stat('.')
>>> s.st_uid
>>> s.st_gid

st_uid is the user id of the owner, st_gid is the group id. See the linked documentation for other information that can be acuired through stat.

I tend to use os.stat:

Perform a stat system call on the given path. The return value is an object whose attributes correspond to the members of the stat structure, namely: st_mode (protection bits), st_ino (inode number), st_dev (device), st_nlink (number of hard links), st_uid (user id of owner), st_gid (group id of owner), st_size (size of file, in bytes), st_atime (time of most recent access), st_mtime (time of most recent content modification), st_ctime (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows)

There’s an example at the link to os.stat above.

Use the os.stat function.

If you are using Linux, it is much easier.
Install tree with the command yum install tree. Then execute the command ‘tree -a -u -g’

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .