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

夙愿已清 提交于 2019-11-30 06:44:19

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

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!