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.
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)
example.txt
exists:The file 'example.txt' exists.
The file 'example.txt' exists.
example.txt
does not exist:file 'example.txt' does not exist.
The file 'example.txt' does not exist.
os.path.exists()
:
os.path.exists(filename)
method checks whether the file exists.pathlib.Path.is_file()
:
Path(filename).is_file()
method from the pathlib
module checks if the given path corresponds to a file.True
only if the path points to a valid file (not a directory)."example.txt"
, checking its existence using both methods.This approach ensures that you can verify file existence before performing operations like reading or modifying it, thus preventing errors.