Python Fileoperations: Check if File exists

In this Python tutorial, we will learn how to check if a file exists before performing operations on it. This is useful to avoid errors when trying to read, write, or modify a file that may not be present. Python provides several ways to check for file existence, including using the os module and the pathlib module. We will demonstrate both approaches.


Code Example:

import os
from pathlib import Path

# Method 1: Using os.path.exists()
def check_file_os(filename):
    if os.path.exists(filename):
        print(f"The file '{filename}' exists.")
    else:
        print(f"The file '{filename}' does not exist.")

# Method 2: Using pathlib.Path
def check_file_pathlib(filename):
    file_path = Path(filename)
    if file_path.is_file():
        print(f"The file '{filename}' exists.")
    else:
        print(f"The file '{filename}' does not exist.")

# Specify the file name
file_name = "example.txt"

# Check if the file exists using both methods
check_file_os(file_name)
check_file_pathlib(file_name)

Output (Example Scenarios):

If example.txt exists:

The file 'example.txt' exists.
The file 'example.txt' exists.

If example.txt does not exist:

file 'example.txt' does not exist.
The file 'example.txt' does not exist.

Code Explanation:

  1. Using os.path.exists():
    • The os.path.exists(filename) method checks whether the file exists.
    • It prints an appropriate message based on whether the file is found or not.
  2. Using pathlib.Path.is_file():
    • The Path(filename).is_file() method from the pathlib module checks if the given path corresponds to a file.
    • It returns True only if the path points to a valid file (not a directory).
  3. Execution:
    • The function is tested with "example.txt", checking its existence using both methods.
    • The result is printed accordingly.

This approach ensures that you can verify file existence before performing operations like reading or modifying it, thus preventing errors.