Reputation: 3
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, i.e. 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,
Upvotes: 0
Views: 3907