Python - Test Read Permissions

4

Is there a function that returns, in Python, True if I have read permissions on the file in python?

    
asked by anonymous 04.03.2015 / 00:31

1 answer

3

You can use the access(path, mode) function of the os .

See an example:

if os.access("foo.txt", os.R_OK):
    with open("foo.txt") as fp:
        # Fazer algo aqui

The first parameter of the function is the path of the file to be scanned, and the second parameter is used to specify the mode to be used.

Modes are:

  • os.F_OK : To test the existence of path .
  • os.R_OK : Used to check if path can be read.
  • os.W_OK : To check the writeability of path .
  • os.X_OK : To check if path can be executed.

Alternatively you can use the stat function also belonging to the module os in conjunction with the helper module stat that allows you to work with a set more options.

import os
import stat

filename = "foo.txt"
if os.path.exists(filename):
    st = os.stat(filename)
    print (bool(st.st_mode & stat.S_IRUSR))
else:
    print ("{0} nao foi encontrado.".format(filename))

We used a bitwise & operation to evaluate whether each output is < in> 1 if the corresponding bit of the attribute ST_MODE and S_IRUSR is 1 , if not 0 and we use the result of the operation on bool that will show True or False .

  • ST_MODE : Used to get bits from file protection.
  • S_IRUSR : Owner has read permission.
04.03.2015 / 00:42