Check if a File Exists in Python

In Python, you can check if a file exists in a directory using the os.path.exists() or pathlib.Path.exists() methods. These methods allow you to verify the presence of a file before performing operations like reading or writing. In this tutorial, we will explore multiple ways to check if a file exists with detailed explanations and examples.


Examples to Check if a File Exists

1. Using os.path.exists() to Check if a File Exists

We will use the os.path.exists() function from the os module to check if a file exists in a directory. This method returns True if the file or directory exists; otherwise, it returns False.

main.py

</>
Copy
import os

# Define the file path
file_path = "example.txt"

# Check if the file exists
if os.path.exists(file_path):
    print("File exists.")
else:
    print("File does not exist.")

Explanation:

  1. We import the os module, which provides functions for interacting with the operating system.
  2. We define the file path using the variable file_path, which stores the filename as a string.
  3. The function os.path.exists(file_path) checks if the specified file exists in the directory.
  4. If the file exists, it prints "File exists."; otherwise, it prints "File does not exist.".

Output:

2. Using os.path.isfile() to Check Only for Files

The os.path.isfile() method checks if a specific path refers to a file and not a directory.

main.py

</>
Copy
import os

# Define the file path
file_path = "example.txt"

# Check if the file exists and is a file (not a directory)
if os.path.isfile(file_path):
    print("File exists.")
else:
    print("File does not exist or is not a file.")

Explanation:

  1. We use os.path.isfile(file_path) instead of os.path.exists() to ensure the path is specifically a file.
  2. If the path exists and is a file, it prints "File exists."; otherwise, it prints "File does not exist or is not a file.".

Output:

If you use, a non-existing file, like for example non-existent-file.txt, you would get the following output.

3. Using pathlib.Path.exists() from the pathlib Module

The pathlib module provides an object-oriented approach to handling file system paths. The Path.exists() method checks if a file or directory exists.

main.py

</>
Copy
from pathlib import Path

# Define the file path
file_path = Path("example.txt")

# Check if the file exists
if file_path.exists():
    print("File exists.")
else:
    print("File does not exist.")

Explanation:

  1. We import Path from the pathlib module.
  2. We create a Path object with file_path = Path("example.txt").
  3. The method file_path.exists() checks if the file or directory exists.
  4. If it exists, it prints "File exists."; otherwise, it prints "File does not exist.".

Output:

4. Using try-except to Check File Existence

We can also check if a file exists by attempting to open it and handling the exception if it does not exist.

main.py

</>
Copy
try:
    # Try to open the file
    with open("non-present.txt", "r") as file:
        print("File exists.")
except FileNotFoundError:
    print("File does not exist.")

Explanation:

  1. We use a try block to attempt opening the file in read mode ("r").
  2. If the file exists, it opens successfully, and we print "File exists.".
  3. If the file does not exist, a FileNotFoundError is raised, and we handle it in the except block by printing "File does not exist.".

Output:

Conclusion

In summary, here are different ways to check if a file exists in Python:

  1. os.path.exists(): Checks if a file or directory exists.
  2. os.path.isfile(): Ensures the path is a file, not a directory.
  3. pathlib.Path.exists(): A modern, object-oriented approach.
  4. try-except: Attempts to open a file and catches FileNotFoundError.