目次
1. Why Check for File Existence in Python
Introduction
Verifying that a file exists is essential for improving program stability. For example, when reading or writing data, if the target file does not exist, an error occurs and the program execution is halted. In Python, there are several ways to check for a file’s existence, and it’s important to choose the method best suited to the specific scenario. This article introduces file-checking methods using theos
module, the pathlib
module, and the glob
module, and explains the advantages of each approach.2. Basic Approach: os Module
How to Use os.path.exists()
os.path.exists()
is used to check whether the specified path exists as a file or directory. This function returns True
if it exists and False
if it does not.import os
if os.path.exists("example.txt"):
print("The file exists")
else:
print("The file does not exist")
This code checks whether example.txt
exists and displays a message based on the result. os.path.exists()
is a generic method that can check both files and directories.Choosing Between os.path.isfile() and os.path.isdir()
os.path.exists()
does not differentiate between files and directories, but using os.path.isfile()
or os.path.isdir()
allows you to determine whether the target is a file or a directory.if os.path.isfile("example.txt"):
print("This is a file")
elif os.path.isdir("example.txt"):
print("This is a directory")
else:
print("It does not exist")
In this way, after confirming the existence of the target, determining whether it is a file or a directory enables more fine-grained operations.
3. Advanced: pathlib Module
Using the Path.exists() Method
pathlib
you can use the Path.exists()
method to check whether a file or directory exists. Like os.path.exists()
, it returns True
or False
, but the code becomes more concise.from pathlib import Path
file_path = Path("example.txt")
if file_path.exists():
print("The file exists")
else:
print("The file does not exist")
With this approach, the file path is treated as a Path
object, so the code is written in an object‑oriented way and is easier to maintain.Path.is_file() and Path.is_dir()
pathlib
also provides the is_file()
and is_dir()
methods, allowing you to easily distinguish whether something is a file or a directory.if file_path.is_file():
print("This is a file")
elif file_path.is_dir():
print("This is a directory")
Thus, by using pathlib
, you can not only check for a file’s existence but also easily determine whether the target is a file or a directory.Real‑World Scenario
pathlib
is especially useful in projects that manipulate multiple directories and files. It lets you write complex path operations simply, and because the same code works across different platforms, it’s ideal for cross‑platform development.4. Checking File Existence in Python: How to Use the glob Module
Pattern Matching with glob
glob
The module allows you to search for files based on filename or path patterns, making it handy when you want to check all files that meet certain criteria at once. It’s especially effective in scenarios involving large numbers of files.import glob
files = glob.glob('*.txt')
if files:
print("Text files found")
else:
print("No text files found")
In this code, we retrieve all .txt
files present in the current directory as a list and verify their existence. Because you can search for files in bulk based on specific file types or patterns, it’s useful for managing backup files and similar tasks.Real-World Scenario
glob
is suitable when working with large numbers of files or folders, or when you need to efficiently process files that match specific names or extensions. For example, it’s ideal for tasks that regularly check and manage log files or temporary files.5. Safe File Operations Using Exception Handling
It’s also important to use exception handling to prevent errors when a file does not exist. By using thetry-except
syntax, you can prevent the program from stopping due to errors and display an error message to the user.try:
with open("example.txt") as f:
print(f.read())
except FileNotFoundError:
print("The file does not exist")
In this code, when a file does not exist, it catches FileNotFoundError
and displays an error message without crashing the program. This improves the user experience and increases the program’s stability.6. Summary
To check for file existence in Python, there are various approaches such as theos
module, pathlib
module, and glob
module. Each method has advantages depending on the scenario, and it’s important to choose the appropriate one.- For simple existence checks,
os.path.exists()
is optimal. - When complex path manipulation or cross‑platform support is needed,
pathlib
is handy. - For pattern‑based searches, the
glob
module is effective.