Before performing file operations, checking “if the file is really there” is very important to prevent errors like FileNotFoundError.
The Python standard library os.path module provides several functions to check for existence. You need to use them differently depending on your purpose, such as when you simply want to know “if it exists” or when you need to distinguish “whether it is a file or a directory”.
This article explains how to use three functions: os.path.exists(), os.path.isfile(), and os.path.isdir().
1. Checking Existence: os.path.exists()
os.path.exists() checks if the specified path exists as a “file” or “directory”. It returns True if it exists, regardless of whether it is a file or a folder.
Syntax:
import os
exists = os.path.exists(path)
Specific Usage Example:
Here is an example of checking if a configuration file exists.
import os
# Path to the file you want to check
config_path = "settings.yaml"
if os.path.exists(config_path):
print(f"Confirmed: '{config_path}' exists.")
else:
print(f"Error: '{config_path}' not found.")
Execution Result (if the file does not exist):
Error: 'settings.yaml' not found.
2. Checking if it is a “File”: os.path.isfile()
os.path.isfile() returns True only if the specified path exists and is a “file”. It returns False if the path is a directory.
Use this when you want to ensure the target is definitely a file, such as before writing to a log file.
import os
target_path = "app_data"
# Strictly check if it is a file
if os.path.isfile(target_path):
print(f"'{target_path}' is a file. Continuing process.")
elif os.path.isdir(target_path):
print(f"'{target_path}' is a directory. It is not a file.")
else:
print(f"'{target_path}' does not exist.")
3. Checking if it is a “Directory”: os.path.isdir()
os.path.isdir() returns True only if the specified path exists and is a “directory”. It returns False if the path is a file.
This is commonly used to check if a destination folder exists, and create it if it does not.
import os
# Output directory
output_dir = "backup_folder"
if not os.path.isdir(output_dir):
print(f"Directory '{output_dir}' does not exist. Creating it.")
os.makedirs(output_dir)
else:
print(f"Directory '{output_dir}' already exists.")
Summary
- os.path.exists(path): Use this when you simply want to know if it exists, regardless of whether it is a file or directory.
- os.path.isfile(path): Use this when you want to confirm it is a file.
- os.path.isdir(path): Use this when you want to confirm it is a directory.
Using these functions correctly allows you to write more robust file manipulation code.
