Monthly Archives: May 2011

Checking File Permissions the Easy Way Using Python

{lang: 'en-GB'}

Edit: Doh! Looks like I forgot something. In Linux, if a file or directory has read, write or executable permissions for the Owner only (nothing for ‘group’ and ‘others’) check_files() doesn’t add a dictionary entry for that path if the user running the script does not own the file or directory. Adding one little ‘elif’ block fixes this. (see the slightly revised code below.)

It never ceases to amaze me what even a wet-behind-the-ears hobbyist like myself can do with Python. I needed a way to get the file permissions and check for the existence of a large number of paths that I could re-use in other scripts. The function shown below is what I came up with.

It takes a Python list containing file/directory paths as an argument and returns a dictionary containing the Paths as keys and the concatenated values ‘READ’, ‘WRITE’, EXECUTE’ separated by commas (or ‘NOACCESS’ if the user doesn’t have read, write or executable permissions) to indicate the users level of access to each path, or just the value ‘NOEXISTS’ if the path does not exist.

def check_files(paths):
        dict = {}
        status=""
        for p in paths:
            if not os.access(p, os.F_OK):
                dict[p]=status=status+"NOEXISTS"
            if(os.access(p,os.R_OK)):
                dict[p]=status=status+"READ," 
            if(os.access(p, os.W_OK)):
               dict[p]=status=status+"WRITE," 
            if (os.access(p, os.X_OK)):
                dict[p]=status=status+"EXECUTE"
            elif os.access(p, os.F_OK) and not (os.access(p,os.R_OK)) and not (os.access(p, os.W_OK)) and not (os.access(p, os.X_OK)):
               dict[p]=status=status="NOACCESS"
            status="" # Set blank before we enter the loop again
        return dict

This function will only give you the permissions for the user running the script but as this was all I needed I did not see that as a major problem. Hope someone finds this useful. As always, you can flame me/prop up my massive ego in the comments :)