Check if a File Exists Before Reading or Writing in Python
To check if a file exists before reading or writing in Python, you can use the os.path.exists()
function or the pathlib.Path.exists()
method. These methods help prevent errors that occur when trying to read a non-existent file or overwrite an existing file unintentionally.
Examples
1. Using os.path.exists()
to Check File Existence
The os.path.exists()
function checks if a file or directory exists before performing operations on it.
main.py
import os
file_path = "example.txt"
# Check if the file exists
if os.path.exists(file_path):
print("The file exists.")
else:
print("The file does not exist.")
Explanation:
- The variable
file_path
stores the name of the file. - The function
os.path.exists(file_path)
checks if the file exists. We are using the returned value as a condition for if-else statement. - If the file exists, the function returns True, it prints
"The file exists."
, otherwise, it prints"The file does not exist."
.
Output:

2. Using pathlib.Path.exists()
for File Existence Check
The pathlib
module provides an object-oriented way to handle filesystem paths.
main.py
from pathlib import Path
file_path = Path("example.txt")
# Check if the file exists
if file_path.exists():
print("The file exists.")
else:
print("The file does not exist.")
Explanation:
Path("example.txt")
creates aPath
object.file_path.exists()
checks if the file exists.- Depending on the result, an appropriate message is printed.
Output:

3. Checking File Existence Before Reading
Before reading a file, it is good practice to check if it exists to avoid FileNotFoundError
.
main.py
import os
file_path = "example.txt"
# Check if the file exists before reading
if os.path.exists(file_path):
with open(file_path, "r") as file:
content = file.read()
print("File Content:\n", content)
else:
print("Error: The file does not exist.")
Explanation:
- The
os.path.exists(file_path)
checks ifexample.txt
exists. - If the file exists, it is opened using
open()
in read mode. - The contents are read and printed.
- If the file does not exist, an error message is displayed.
Output:

4. Checking File Existence Before Writing
Before writing to a file, you may want to check if it already exists to avoid accidental overwriting.
main.py
import os
file_path = "output.txt"
# Check if the file already exists
if os.path.exists(file_path):
print("The file already exists. Choose a different filename.")
else:
with open(file_path, "w") as file:
file.write("Hello, Python!")
print("File created successfully.")
Explanation:
- The
os.path.exists(file_path)
checks ifoutput.txt
exists. - If the file exists, it warns the user.
- If the file does not exist, it creates and writes
"Hello, Python!"
to it.
Output:


If you try to run the program second time, after creating the file, you would get the following output.

Conclusion
In this tutorial, we have covered following methods to check if a file exists before reading or writing in Python:
- Use
os.path.exists()
for simple file existence checks. - Use
pathlib.Path.exists()
for an object-oriented approach. - Always check file existence before reading to avoid
FileNotFoundError
. - Check before writing to prevent overwriting important data.