4
Is there a function that returns, in Python, True
if I have read permissions for the python file?
4
Is there a function that returns, in Python, True
if I have read permissions for the python file?
3
You can use the function access(path, mode)
module os
.
Take 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 file path to be checked and the second parameter is used to specify the mode to be used.
Manners are:
os.F_OK
: To test the existence of path.os.R_OK
: Used to check whether path can be read.os.W_OK
: To verify the writing ability of path.os.X_OK
: To check whether path can be executed.Alternatively you can use the function stat
also belonging to the module os
together with the auxiliary module stat
which allows working with a larger set of 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 use an operation bitwise &
to assess whether each bit output is 1 if the bit corresponding to the attribute ST_MODE
and S_IRUSR
is 1, if it’s not 0 and use the result of the operation in function bool
who will show True or False.
Browser other questions tagged python python-2.7
You are not signed in. Login or sign up in order to post.
The part "with open("foo.txt") as Fp:" is even required ?
– Help Needed 101
@Helpneeded101 Not necessarily used only as an example.
– stderr