简体   繁体   中英

How to test if a file is readable in python without opening the file?

Would like to test if a file is readable in python on a linux system by checking its attributes/permissions.

New to python and I am looking for the equivalent of the following from perl/bash.

[[ -r ${filename} ]]

or

if ( -r $filename ) {...}

I just do an open on the file to check if its readable:

def isFileReadable2 (filename):
    # check to see if file is readable
    # by trying to open a file in readonly mode
    # if an exception occurs,
    # then either the file didnt exist, or file was NOT readable
    try:
        import stat
        mode = os.stat(filename).st_mode
        fh = open (filename, 'r')
    except IOError as err:
        print ("Error opening file {}:{}\n". format (filename, err))
    else:
        fh.close ()
        return True
    return False

I did notice that stat_result's bit pattern corresponded to the files permissions, ie st_mode=32832 translates to 0b1000000001000000, which in turn tells me that this file is user executable only, and not readable at all, which happens to be correct.

So, while I could check using the proper bit masks, is there a better portable interface to the os.stat_result object? and in particular the st_mode value?

Thought of using os.fstat, but that returns the same stat_result object.

tia,

您可以使用函数os.access

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM