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

前端 未结 7 1641
青春惊慌失措
青春惊慌失措 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:19

    I stumbled across this recently, looking to get owner user and group information, so I thought I'd share what I came up with:

    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
        )
    

提交回复
热议问题