- 1 year ago
How to check if a read-only file exists
To check if a read-only file exists in Python, you can use the os.path.isfile()
function to test if the file exists and the os.access()
function to test if the file is readable.
Here's an example of how you can implement this:
pythonimport os
filename = 'example.txt'
if os.path.isfile(filename) and os.access(filename, os.R_OK):
print(f"{filename} exists and is readable")
else:
print(f"{filename} does not exist or is not readable")
In this example, we first check if the file example.txt
exists using the os.path.isfile()
function. If the file exists, we then check if it is readable using the os.access()
function with the os.R_OK
flag. If the file is both a file and readable, we print a message indicating that the file exists and is readable. Otherwise, we print a message indicating that the file does not exist or is not readable.
Note that the os.access()
function can also be used to test for other types of permissions, such as write or execute permissions. You can use the appropriate flags (os.W_OK
and os.X_OK
, respectively) to test for these permissions.