how to find the owner of a file or directory in python how to find the owner of a file or directory in python python python

how to find the owner of a file or directory in python


I'm not really much of a python guy, but I was able to whip this up:

from os import statfrom pwd import getpwuiddef find_owner(filename):    return getpwuid(stat(filename).st_uid).pw_name


You want to use 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)

Example of usage to get owner UID:

from os import statstat(my_filename).st_uid

Note, however, that stat returns user id number (for example, 0 for root), not actual user name.


It's an old question, but for those who are looking for a simpler solution with Python 3.

You can also use Path from pathlib to solve this problem, by calling the Path's owner and group method like this:

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

So in this case, the method could be the following:

from typing import Unionfrom pathlib import Pathdef find_owner(path: Union[str, Path]) -> str:    path = Path(path)    return f"{path.owner()}:{path.group()}"