Python 3 – os.access() Method
Have you ever wanted to check whether or not a file or directory is accessible? Well look no further, the os.access()
method in Python 3 can tell you just that.
Let’s get started with the basics. The os.access()
method checks the rights that a particular user has to a file, directory or path. It returns True
if the required access rights are available, otherwise, it returns False
.
Syntax
The syntax for the os.access()
method is as follows:
os.access(path, mode)
Where:
path
: This is the path to the file or directory that you want to check access for.mode
: This is the access mode that you want to check for.
The mode
parameter can be one of the following constants:
os.F_OK
: Tests the existence of the path.os.R_OK
: Tests for read access.os.W_OK
: Tests for write access.os.X_OK
: Tests for execute access.
You can pass one or more of these constants by ORing them together. For example, the following code checks for read and write access to a file:
os.access("/path/to/file.txt", os.R_OK | os.W_OK)
Example Code
To get a better understanding of how os.access()
works, let’s take a look at some example code.
import os
path = "/path/to/file.txt"
if os.access(path, os.F_OK):
print(f"{path} exists.")
else:
print(f"{path} does not exist.")
if os.access(path, os.R_OK):
print(f"You have read access to {path}.")
else:
print(f"You do not have read access to {path}.")
if os.access(path, os.W_OK):
print(f"You have write access to {path}.")
else:
print(f"You do not have write access to {path}.")
if os.access(path, os.X_OK):
print(f"You have execute access to {path}.")
else:
print(f"You do not have execute access to {path}.")
In this code, we first define a path to a file called file.txt
. We then use the os.access()
method to check whether or not the file exists, and whether we have read, write and execute access to it.
The output of this code should be something like:
/path/to/file.txt exists.
You have read access to /path/to/file.txt.
You have write access to /path/to/file.txt.
You do not have execute access to /path/to/file.txt.
Conclusion
The os.access()
method is a simple and convenient way to check the access to a path, file or directory. Remember to pass the correct mode to the method, and you’ll be able to determine whether or not you have the required access rights.