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

前端 未结 7 1672
青春惊慌失措
青春惊慌失措 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 04:58

    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 Path
    
    path = 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 Union
    from pathlib import Path
    
    def find_owner(path: Union[str, Path]) -> str:
        path = Path(path)
        return f"{path.owner()}:{path.group()}"
    

提交回复
热议问题