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

Recommended Answers

All 2 Replies

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"

import os, stat, pwd

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

    for current in thisDir:

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



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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.