dan
dan

Reputation: 595

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

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

Upvotes: 27

Views: 32814

Answers (6)

Raviteja Reddy
Raviteja Reddy

Reputation: 1

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'

Upvotes: 0

loxaxs
loxaxs

Reputation: 2279

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" % whatever.group())

Upvotes: 13

Ayman Hourieh
Ayman Hourieh

Reputation: 137206

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

Upvotes: 48

Stephan202
Stephan202

Reputation: 61529

Use os.stat:

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

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.

Upvotes: 1

eduffy
eduffy

Reputation: 40222

Use the os.stat function.

Upvotes: 0

Jarret Hardie
Jarret Hardie

Reputation: 97962

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.

Upvotes: 0

Related Questions