Use os.access() with os.R_OK
In this step, we will use the os.access()
function in Python to check if a file has read permissions. The os.access()
function takes two arguments: the file path and a permission flag. We will use os.R_OK
to check for read permissions.
First, let's create a new Python file named check_permissions.py
in the ~/project
directory. Open the VS Code editor and add the following code to the file:
import os
file_path = "my_script.py"
## Check if the file exists
if not os.path.exists(file_path):
print(f"Error: The file '{file_path}' does not exist.")
else:
## Check if the file has read permissions
if os.access(file_path, os.R_OK):
print(f"The file '{file_path}' has read permissions.")
else:
print(f"The file '{file_path}' does not have read permissions.")
Save the file. This script first checks if the file my_script.py
exists. If it does, it then uses os.access()
with os.R_OK
to check if the file has read permissions. The script will print a message indicating whether or not the file has read permissions.
Now, run the script from the terminal:
python check_permissions.py
You should see the following output:
The file 'my_script.py' has read permissions.
This is because, by default, the file my_script.py
has read permissions for the owner, group, and others.
Now, let's modify the permissions of the my_script.py
file to remove read permissions for everyone except the owner. We can do this using the chmod
command in the terminal.
chmod 600 my_script.py
This command sets the permissions of my_script.py
to read and write for the owner only (600 in octal notation).
Now, run the check_permissions.py
script again:
python check_permissions.py
You should now see the following output:
The file 'my_script.py' does not have read permissions.
This is because we have removed read permissions for the group and others. The os.access()
function correctly identifies that the file no longer has read permissions for the user running the script (which is labex
).
Finally, let's restore the original permissions of the my_script.py
file:
chmod 644 my_script.py
This command sets the permissions of my_script.py
to read and write for the owner and read-only for the group and others (644 in octal notation).