How to convert stat output to unix permission string

If you run os.stat(path) in a file and then take its st_mode parameter, how do you get from there to this line: rw-r--r-- , as you know from the Unix world?

+7
python
source share
3 answers

With Python 3.3, you can use stat.filemode :

 In [7]: import os, stat In [8]: print(stat.filemode(os.stat('/home/soon/foo').st_mode)) -rw-r--r-- In [9]: ls -l ~/foo -rw-r--r-- 1 soon users 0 Jul 23 18:15 /home/soon/foo 
+11
source share

Something like that:

 import stat, os def permissions_to_unix_name(st): is_dir = 'd' if stat.S_ISDIR(st.st_mode) else '-' dic = {'7':'rwx', '6' :'rw-', '5' : 'r-x', '4':'r--', '0': '---'} perm = str(oct(st.st_mode)[-3:]) return is_dir + ''.join(dic.get(x,x) for x in perm) ... >>> permissions_to_unix_name(os.stat('.')) 'drwxr-xr-x' >>> ls -ld . drwxr-xr-x 62 monty monty 4096 Jul 23 13:23 ./ >>> permissions_to_unix_name(os.stat('so.py')) '-rw-rw-r--' >>> ls -ld so.py -rw-rw-r-- 1 monty monty 68 Jul 18 15:57 so.py 
+4
source share

The following function will achieve this, given some common circumstances (i.e. I have not tested it under Windows or SELinux).

 import stat def permissions_to_unix_name(st_mode): permstr = '' usertypes = ['USR', 'GRP', 'OTH'] for usertype in usertypes: perm_types = ['R', 'W', 'X'] for permtype in perm_types: perm = getattr(stat, 'S_I%s%s' % (permtype, usertype)) if st_mode & perm: permstr += permtype.lower() else: permstr += '-' return permstr 

This creates the main string on demand. However, this can also be improved to display additional data, for example. be it a directory ( d ) or a symbolic link ( l ). Feel free to improve it.

+2
source share

All Articles