How to check the permissions of a file using Python?


File permissions in Python empower you to determine who can perform certain operations on a file. These file attributes include read, write, and execute permissions. The os module in Python, especially the os.chmod() function in the os module, is used to set or modify permissions. The os.stat() function belonging to os module can be used to check the current permissions of a file. Managing and manipulating file permissions is important and critical for security and access control in Python programs.

Checking file permissions in Python is important for ensuring the security and integrity of the data stored in files.

  • File permissions determine and decide who can access, modify, or execute a file in a computer system.

  • By checking file permissions in Python, you can control and limit access to sensitive files, stopping unauthorized users from viewing or modifying them.

  • It helps to prevent accidental or deliberate tampering with critical files, protecting the integrity and confidentiality of data.

  • File permission checks are crucial for enforcing user-level security; as different users may have different levels of access to files.

  • Verifying file permissions is especially important when dealing with sensitive and confidential information, such as personal or financial data.

  • It permits you to implement access controls and only grant privileges to trusted individuals or authorized processes.

  • By examining file permissions automatically, you can detect any inconsistencies or unauthorized intrusions and changes made to the permissions themselves.

  • This process of checking file permissions contributes to the overall security profile of an application or system, at the same time, minimizing the risk of data breaches or unauthorized access.

To check the permissions of a file in Python, you can import and utilize the os module, as we have already mentioned above. This os module is very useful and provides several functions for interacting with the operating system. Specifically, you can utilize the os.access() function of the os module to determine the extent of file accessibility based on its permissions.

Checking the Permissions of a File Using os.access()

Example

Here, in this code example, we define the check_file_permissions() function that takes a file_path parameter as an argument. We make use of the os.access() function of the os module to check the permissions for the file at the designated path. The os.R_OK, os.W_OK, and os.X_OK constants symbolize read, write, and execute permissions, respectively, in that order.

This function checks each permission separately and consequently prints out a message stating explicitly if the permission is granted or not for the given file.

By running and executing this code, it will be seen that you can easily find the permissions of a file in Python.

import os
def check_file_permissions(file_path):
   if os.access(file_path, os.R_OK):
      print(f"Read permission is granted for file: {file_path}")
   else:
      print(f"Read permission is not granted for file: {file_path}")
    
   if os.access(file_path, os.W_OK):
      print(f"Write permission is granted for file: {file_path}")

   else:
      print(f"Write permission is not granted for file: {file_path}")
    
   if os.access(file_path, os.X_OK):
      print(f"Execute permission is granted for file: {file_path}")
   else:

      print(f"Execute permission is not granted for file: {file_path}")
# Example usage
file_path = "path/to/file.txt"
check_file_permissions(file_path)

Output

For some file1.txt, the following is the output

Read permission is granted for file: /file1.txt
Write permission is granted for file: /file1.txt
Execute permission is not granted for file: /file1.txt

Making Use of the Stat Module

Example

At first, we import both os and stat modules. Here, in this example, we use the os.stat() function to fetch the file's status information, including the file mode. The file mode represents and symbolizes the permissions of the file. We then deploy bitwise operations with the constants from the stat module (e.g., stat.S_IRUSR for read permission of the owner) to check and verify the individual file permissions.

import os
import stat

def check_file_permissions(file_path):
   file_stat = os.stat(file_path)
   file_mode = file_stat.st_mode

   if stat.S_IRUSR & file_mode:
      print(f"Read permission is granted for the owner of file: {file_path}")
   else:
      print(f"Read permission is not granted for the owner of file: {file_path}")

    if stat.S_IWUSR & file_mode:
        print(f"Write permission is granted for the owner of file: {file_path}")
    else:
        print(f"Write permission is not granted for the owner of file: {file_path}")

    if stat.S_IXUSR & file_mode:
        print(f"Execute permission is granted for the owner of file: {file_path}")
    else:
        print(f"Execute permission is not granted for the owner of file: {file_path}")

# Example usage
file_path = "path/to/file.txt"
check_file_permissions(file_path)

Output

For some file1.txt, the following is the output

Read permission is granted for the owner of file: /file1.txt
Write permission is granted for the owner of file: /file1.txt
Execute permission is not granted for the owner of file: /file1.txt

Making Use of the pathlib module

Here, we leverage and make use of the pathlib module's Path class to create a Path object pointing to the file. We also import the os module. We can then use the os module's access() function to check the permissions of a file.

Example

import os
from pathlib import Path

def check_file_permissions(file_path):
   file = Path(file_path)

   if file.is_file():
      if os.access(file_path, os.R_OK):
         print(f"Read permission is granted for file: {file_path}")
      else:
         print(f"Read permission is not granted for file: {file_path}")

      if os.access(file_path, os.W_OK):
         print(f"Write permission is granted for file: {file_path}")
      else:
         print(f"Write permission is not granted for file: {file_path}")

      if os.access(file_path, os.X_OK):
         print(f"Execute permission is granted for file: {file_path}")
      else:
         print(f"Execute permission is not granted for file: {file_path}")
   else:
      print(f"The specified path does not point to a file: {file_path}")

# Example usage

file_path = "path/to/file.txt"
check_file_permissions(file_path)

Output

For some file1.txt, the following is the output

Read permission is granted for file: /file1.txt
Write permission is granted for file: /file1.txt
Execute permission is not granted for file: /file1.txt

Making Use of the os.access() function

We utilize the os.access() function, in this example, to check the file permissions. It takes the file path and a mode parameter (e.g., os.R_OK for read permission) as arguments and returns True if the specified permission is granted, else it returns False.

Example

import os
def check_file_permissions(file_path):
   if os.access(file_path, os.R_OK):
      print(f"Read permission is granted for file: {file_path}")
   else:
      print(f"Read permission is not granted for file: {file_path}")

   if os.access(file_path, os.W_OK):
      print(f"Write permission is granted for file: {file_path}")
   else:
      print(f"Write permission is not granted for file: {file_path}")

   if os.access(file_path, os.X_OK):
      print(f"Execute permission is granted for file: {file_path}")

   else:
      print(f"Execute permission is not granted for file: {file_path}")

# Example usage
file_path = "path/to/file.txt"
check_file_permissions(file_path)

Output

For some file1.txt, it gives following output

Read permission is granted for file: /file1.txt
Write permission is granted for file: /file1.txt
Execute permission is not granted for file: /file1.txt

Making Use of the os.path module

We combine various functions and methods from the os.path module, in this example, to carry out a more comprehensive check. At first, we check if the path points to a file using os.path.isfile(). Then, we verify if the file, in fact, exists and is not empty using os.path.exists() and os.path.getsize() methods. Finally, we use os.access() to check the file permissions provided all the conditions are met.

Example

import os
def check_file_permissions(file_path):
   if os.path.isfile(file_path):
      if os.path.exists(file_path) and 
os.path.getsize(file_path) > 0:
         print(f"File exists and is not empty: {file_path}")
         if os.access(file_path, os.R_OK):
            print(f"Read permission is granted for file: 
{file_path}")
         else:
                print(f"Read permission is not granted for file:
{file_path}")
      else:
         print(f"File does not exist or is empty: 
{file_path}")
   else:
      print(f"Path does not point to a file: {file_path}")

# Example usage
file_path = "path/to/file.txt"
check_file_permissions(file_path)

Output

For some file1.txt, the following is the output

File exists and is not empty: /file1.txt
Read permission is granted for file: /file1.txt    

Checking file permissions in Python is of great importance in multi-user environments, where several individuals or processes may interact and work with the same files. We have seen different strategies and modules and their functions to check file permissions in this article and also seen alternative ways to do the same.

To conclude, by properly checking, managing, and validating file permissions, you augment the overall reliability and security of your Python applications and systems.

Updated on: 17-Jul-2023

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements