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
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()}"