如何在Python中查找文件或目录的拥有者

48 投票
7 回答
75635 浏览
提问于 2025-04-15 16:35

我需要一个在Python中用来查找文件或目录拥有者的函数或方法。

这个函数应该像这样:

>>> find_owner("/home/somedir/somefile")
owner3

7 个回答

23

你想使用 os.stat() 这个功能:

os.stat(path)
 Perform the equivalent of a stat() system call on the given path. 
 (This function follows symlinks; to stat a symlink use lstat().)

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)

下面是一个获取文件拥有者用户ID的例子:

from os import stat
stat(my_filename).st_uid

不过要注意,stat 返回的是用户的ID号码(比如,0代表超级用户root),而不是实际的用户名。

31

这是一个老问题,但对于那些想用Python 3找到更简单解决方案的人来说,这里有个好方法。

你可以使用来自pathlibPath来解决这个问题,方法是调用Pathownergroup方法,像这样:

from pathlib import Path

path = Path("/path/to/your/file")
owner = path.owner()
group = path.group()
print(f"{path.name} is owned by {owner}:{group}")

所以在这种情况下,方法可以是这样的:

from typing import Union
from pathlib import Path

def find_owner(path: Union[str, Path]) -> str:
    path = Path(path)
    return f"{path.owner()}:{path.group()}"
94

我对Python不是很熟悉,但我还是能快速写出这个代码:

from os import stat
from pwd import getpwuid

def find_owner(filename):
    return getpwuid(stat(filename).st_uid).pw_name

撰写回答