如何在python中找到文件或目录的所有者

2024-09-25 16:34:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要Python中的函数或方法来查找文件或目录的所有者。

函数应该如下:

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

Tags: 方法函数目录homefindsomefileownersomedir
3条回答

要使用^{}

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)

获取所有者UID的用法示例:

from os import stat
stat(my_filename).st_uid

但是,请注意,stat返回的是用户id号(例如,0代表根),而不是实际的用户名。

我不是一个很喜欢Python的人,但我能把它激发出来:

from os import stat
from pwd import getpwuid

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

我最近无意中发现了这一点,希望获得所有者用户和组的信息,所以我想分享一下我的想法:

import os
from pwd import getpwuid
from grp import getgrgid

def get_file_ownership(filename):
    return (
        getpwuid(os.stat(filename).st_uid).pw_name,
        getgrgid(os.stat(filename).st_gid).gr_name
    )

相关问题 更多 >