Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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/somefile") owner3 
like image 565
ramdaz Avatar asked Dec 02 '09 04:12

ramdaz


People also ask

How do you show the owner of a file in Python?

stat. It gives you st_uid which is the user ID of the owner. Then you have to convert it to the name. To do that, use pwd.

How do I find out who owns a directory?

The best Linux command to find file owner is using “ls -l” command. Open the terminal then type ls -l filename in the prompt. The 3rd column is the file owner.

How do I change the owner of a file in Python?

chown() method in Python is used to change the owner and group id of the specified path to the specified numeric owner id (UID) and group id (GID). Note: os. chown() method is available only on UNIX platforms and the functionality of this method is typically available only to the superuser or a privileged user.


1 Answers

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

from os import stat from pwd import getpwuid  def find_owner(filename):     return getpwuid(stat(filename).st_uid).pw_name 
like image 88
asveikau Avatar answered Sep 21 '22 19:09

asveikau