Skip to main content

How to Check If a File Is Readable in Python

Before reading a file, it is often necessary to check permissions to prevent your program from crashing. In Linux/Unix systems, file permissions determine whether the current user can read (r), write (w), or execute (x) a file.

This guide explains how to check read permissions in Python using the os module and robust error handling.

Understanding File Permissions​

Every file has associated permissions for the Owner, Group, and Others.

  • Read (r): Permission to view content.
  • Write (w): Permission to modify content.
  • Execute (x): Permission to run the file as a program.

If a script tries to open() a file without read permission, Python raises a PermissionError.

Method 1: Using os.access() (Pre-Check)​

The os.access() function allows you to check a specific permission flag for a file path without opening it.

  • os.R_OK: Read permission.
  • os.W_OK: Write permission.
  • os.X_OK: Execute permission.
import os

file_path = "my_script.py"

# 1. Check existence first
if not os.path.exists(file_path):
print("File does not exist.")
else:
# 2. Check read permission
# os.access returns True if the permission is granted
if os.access(file_path, os.R_OK):
print(f"Readable: Yes")
else:
print(f"Readable: No (Permission Denied)")
warning

Time-of-Check to Time-of-Use (TOCTOU) Bug: Relying solely on os.access() is not 100% safe in concurrent environments. Permissions could change between the time you check os.access() and the time you actually open() the file.

Method 2: Using try-except (Robust Handling)​

The most robust, Pythonic way to handle permissions is to attempt the operation and catch the specific error if it fails. This avoids race conditions (TOCTOU bugs).

file_path = "restricted_data.txt"

try:
# Attempt to open
with open(file_path, "r") as file:
print("File opened successfully.")
print(file.read())

except PermissionError:
# ✅ Correct: Specific handling for permission issues
print(f"Error: You do not have permission to read '{file_path}'.")

except FileNotFoundError:
print(f"Error: '{file_path}' does not exist.")

except OSError as e:
# Catch-all for other I/O errors (disk full, corrupted, etc.)
print(f"Unexpected I/O error: {e}")

Conclusion​

To check if a file is readable in Python:

  1. Use try-except PermissionError as your primary strategy. It is robust and handles the reality of the file system at the exact moment of access.
  2. Use os.access(path, os.R_OK) if you only need to check permissions (e.g., for a status report UI) without actually opening the file.