Check if a File or Directory Exists using Python

A document is a compilation of data or details kept on a computer under a particular title. It could be a record, a picture, a film, software, or any other type of information. Documents may come with additions that display their extensions, such as .txt, .jpg, .py, .html, etc. Conversely, a file, also known as a directory, is a holder within a file system. It acts as a means to arrange and hoard documents and other directories. Let's explore how documents and directories are managed.

Check if a File or Directory Exists using Python

Sometimes, we want to confirm whether a folder exists in our file system. It is important to confirm whether a directory or document exists to prevent an existing file from being overwritten or to ensure it is accessible before opening it. We have many ways to do this, no matter if it is a letter or a record. You can use the following methods to check whether a file or directory exists:

  1. Using os.path.exists() method
  2. Using os.path.isfile() method
  3. Using os.path.isdir() method
  4. Using pathlib.Path.exists() method

Using os.path.exists() Method

The Python OS module is one of Python's standard modules. It provides several functions for interacting with the operating system.

The os.path component is a subset of the Operating System module in Python for standard path names. The os.path.exists() function is used to verify the presence of a particular path. This function helps determine if a particular file or folder exists. In addition, we can also use the functions to ensure that the path denotes a valid file description.

Syntax:

  • Purpose of Using:
    We use this method to check if the specified route is present in the filesystem.
  • Parameter:
    An object resembling a pathway within a file system where it can be a string or bytes object.
  • Return Value:
    It returns a Boolean result if the route is present; the result will be True. False if not.

Example:

Output:

Path 'C:/Users/hp/Desktop/example.txt' exists: True
Path 'C:/Users/Desktop/demo.txt' exists: False

Explanation:

The above code checks whether the specified paths exist using the os.path.exists() function. After importing the 'os' module, we check if the provided paths exist, and it will print True otherwise False.

Using os.path.isfile() Method

The os module in Python contains a function called isfile() that is utilized to verify the presence of a file. It checks whether the specified path is an existing regular file or not.

Syntax:

  • Purpose of Using:
    Check to see if the provided location leads to a current standard document.
  • Parameters:
    A path-like object representing a file system path. This can be either a string or bytes object.
  • Return Type:
    Checks whether the specified path is a valid regular file and returns a boolean value of True or False if it is not.

Example:

Output:

Path 'C:/Users/hp/Desktop/example.txt' is a file: True
Path 'C:/Users/Desktop/demo.txt' is a file: False

Explanation:

In the above code, we checked the presence of provided paths using the `os.path.isfile()` function. For the first path: 'C:/Users/hp/Desktop/example.txt', it checks if the file path is available and returns True. The second path, 'C:/Users/Desktop/demo.txt', checks if the provided path is available. It will give the result True; otherwise, it will be False.

Using os.path.isdir() Method

The Python method os.path.isdir() ensures that the designated location is in the current folder. This method follows a symbolic link, which means if the provided path is the symbolic link detecting a directory, then the output will be True.

Syntax:

  • Purpose of Using:
    Check if the specified route leads to a current folder.
  • Parameters:
    A path-like object representing a file system path. This can be either a string or bytes object.
  • Return Type:
    It returns a Boolean outcome.

Example:

Output:

Path 'C:/Users/hp/Desktop/example.txt' is a directory: False
Path 'C:/Users/hp/Desktop/demo.txt' is a directory: False

Explanation:

The above code checks if the specified paths point to directories using the `os.path.isdir()` function. For the first path, 'C:/Users/hp/Desktop/example.txt', it checks if it points to a directory and prints the result. For the second path, 'C:/Users/hp/Desktop/demo.txt', it checks if it points to a directory and prints the result.

Using pathlib.Path.exists() Method

The Python Pathlib module offers several classes with semantics suitable for different operating systems that describe file system paths. This module is included in the standard utility modules for Python. The Pathlib module has two types of route classes: pure paths and concrete paths. Concrete pathways derived from pure paths offer computational and I/O activities, whereas pure paths solely offer computational actions.

Syntax:

  • Purpose of Using:
    Determining if the designated route is present within the vicinity.
  • Parameters:
    Path: An object resembling a pathway within a file system (could be a string or bytes object).
  • Return Type:
    The function will provide a Boolean outcome, indicating whether the specified location is valid (True) or not (False).

Example:

Output:

Path 'C:\Users\hp\Desktop\demo.txt' exists.

Explanation:

This code uses the `Path` class from the `pathlib` module to check if a specified path exists and points to a file or directory. It imports the `Path` class from the `pathlib` module. It instantiates the `Path` class with the specified path 'C:\Users\hp\Desktop\demo.txt'. It uses the `exists()` method to check if the path points to an existing file or directory and then prints the result.

Another Method: Using try/except Block

In this approach, we attempt to open the file (or access the path) within a try block. If the file or directory exists, the code inside the try block executes successfully. If the file or directory does not exist, an exception is raised, and we catch it in the except block.

Example:

Output:

The file exists!

Explanation:

The above code attempts to read the file 'demo.txt' located at 'C:\Users\hp\Desktop\' using the 'with' statement. If the file exists, 'File exists!' It printed. It prints ' no file ' if it is not found (FileNotFoundError).

Conclusion

Python offers various techniques to confirm the presence of files and folders. The os.path module includes functions like exists(), isfile(), isdir() and pathlib.Path.exists(). In addition, the pathlib module introduces a Path class with functions such as is_file() and is_dir(). The selection between these Python methods depends on your coding style and references. Whatever methods you use, confirming the presence helps diagnose and optimise document organisation in your Python scripts.