0

(Linux)

output = os.listdir()

In the above line of code I'm getting the name of the file(s) in a given directory, but how can I also get the permissions? This is what I want to see.

-rwxr-xr-x 1 garrett garrett  158 Nov 23 10:49 dirlist.py
drwxr-xr-x 2 garrett garrett 4096 Nov 23 10:32 test.dir
-rw-r--r-- 1 garrett garrett    0 Nov 23 10:32 test.txt
2
Contributors
2
Replies
15
Views
3 Years
Discussion Span
Last Post by lewashby
1

Take a look at the docs for os.stat()

def file_permissions( fname ) :
    st = os.stat(fname)
    ##--- st = tuple, in format
    ##      0    1   2    3    4   5    6    7     8     9
    ##    (mode,ino,dev,nlink,uid,gid,size,atime,mtime,ctime)
    mode = st[0]

    if mode :
        print "st_mode = ", mode
    if mode & stat.S_ISLNK(st[stat.ST_MODE]) :
        print "is link"
    else :
        print "is NOT link"     
    if mode & stat.S_IREAD :
        print "readable"
    if mode & stat.S_IWRITE :
        print "writable"
    if mode & stat.S_IEXEC:
        print "executable"
0
#!/usr/bin/python3

import os, stat, pwd

def list_files():
    thisDir = os.listdir()

    for current in thisDir:
        print(get_current_attr(current))
        #print(current)

def get_current_attr(file):
    line = (stat.filemode(os.stat(file).st_mode))
    line = line + '\t\t ' + (stat.filemode(os.stat(file).st_uid))
    line = line + '\t\t ' + file
    return line

print(list_files())

#END#

Why is the second line in get_current_attr() dispaying almost the exact same thing as the frist line except that it lacks the tail end None, which I atually prefer. I changed st_mode to st_uid but I'm still getting almost the same output. Thanks Woooee, I'' see if I can work that into my program.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.