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

前端 未结 7 1678
青春惊慌失措
青春惊慌失措 2020-12-03 04:38

I need a function or method in Python to find the owner of a file or directory.

The function should be like:

>>> find_owner(\"/home/somedir         


        
7条回答
  •  天涯浪人
    2020-12-03 05:14

    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 stat
    stat(my_filename).st_uid
    

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

提交回复
热议问题