In this tutorial, I will explain how to check if a file exists and create it if not in Python. As a data scientist working on a project, I recently faced an issue where I needed to ensure that a specific file existed before processing it. If the file didn’t exist, I wanted to create it automatically. In this article, I’ll share the solution I found and provide detailed examples to help you understand the process.
Check If a File Exists in Python
Python provides several ways to check if a file exists. The most common methods are using the os.path module or the pathlib library. Let’s explore each method in detail.
Read How to Write a Variable to a File in Python?
1. Use os.path.exists() Method
The os.path module in Python offers the exists() method, which allows you to check if a file or directory exists. You can use this method to check if a file or directory exists.
Here’s an example:
import os
file_path = "C:/Users/JohnDoe/Documents/data.txt"
if os.path.exists(file_path):
print("The file exists.")
else:
print("The file does not exist.")Output:
The file does not exist.You can refer to the screenshot below to see the output.

In this example, we import the os module and specify the file_path variable with the path to the file we want to check. We then use the os.path.exists() method to check if the file exists. If it does, we print “The file exists.” Otherwise, we print “The file does not exist.”
Check out Python Create File
2. Use os.path.isfile() Method
Another method provided by the os.path module is isfile(). This method specifically checks if the given path points to an existing regular file. It follows symbolic links, so it will return True even if the file is a symbolic link to a regular file.
Here’s an example:
import os
file_path = "C:/Users/EmilyJohnson/Documents/report.docx"
if os.path.isfile(file_path):
print("The file exists.")
else:
print("The file does not exist or is not a regular file.")Output:
The file does not exist or is not a regular file.You can refer to the screenshot below to see the output.

In this example, we use os.path.isfile() to check if the file_path points to an existing regular file. If it does, we print “The file exists.” Otherwise, we print “The file does not exist or is not a regular file.”
Read Python Get File Extension
3. Use pathlib.Path.exists() Method
The pathlib library, introduced in Python 3.4, provides an object-oriented approach to working with file paths. You can use the exists() method of the Path class to check if a file exists.
Here’s an example:
from pathlib import Path
file_path = Path("C:/Users/MichaelSmith/Documents/sales_data.csv")
if file_path.exists():
print("The file exists.")
else:
print("The file does not exist.")Output:
The file exists.You can refer to the screenshot below to see the output.

In this example, we import the Path class from the pathlib library and create a Path object with the file_path. We then use the exists() method to check if the file exists. If it does, we print “The file exists.” Otherwise, we print “The file does not exist.”
Check out Python Get Filename From Path
Create a File If It Doesn’t Exist
Now that we know how to check if a file exists, let’s explore how to create it if it doesn’t. We can use the open() function in Python to create a new file.
Here’s an example:
file_path = "C:/Users/SarahWilson/Documents/expenses.txt"
if not os.path.exists(file_path):
with open(file_path, "w") as file:
file.write("This is a new file.")
print("File created successfully.")
else:
print("The file already exists.")Output:
The file already exists.You can refer to the screenshot below to see the output.

In this example, we first check if the file_path exists using os.path.exists(). If it doesn’t exist, we use the open() function with the “w” mode (write mode) to create a new file. We then write some initial content to the file using the write() method. Finally, we print “File created successfully.” If the file already exists, we print “The file already exists.”
Read Python File methods
Check If a File Exists and Create It If Not in Python
Now let’s combine the concepts of checking if a file exists and creating it if it doesn’t into a practical example. Suppose you’re working on a project that requires you to log user activity. You want to check if the log file exists and create it if it doesn’t.
Here’s an example:
import os
from datetime import datetime
log_directory = "C:/Users/JenniferBrown/Documents/logs"
log_file = "activity_log.txt"
log_path = os.path.join(log_directory, log_file)
if not os.path.exists(log_directory):
os.makedirs(log_directory)
print("Log directory created.")
if not os.path.isfile(log_path):
with open(log_path, "w") as file:
file.write("User Activity Log\n")
print("Log file created.")
# Log user activity
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
activity = "User logged in"
log_entry = f"{timestamp} - {activity}\n"
with open(log_path, "a") as file:
file.write(log_entry)
print("User activity logged.")In this example:
- We import the necessary modules:
osfor file and directory operations anddatetimefor timestamp generation. - We define the
log_directoryandlog_filevariables to specify the directory and file name for the log file. - We use
os.path.join()to create the fulllog_pathby combining thelog_directoryandlog_file. - We check if the
log_directoryexists usingos.path.exists(). If it doesn’t, we create it usingos.makedirs(). - We check if the
log_fileexists usingos.path.isfile(). If it doesn’t, we create it usingopen()with the “w” mode and write the initial header. - We generate a
timestampusingdatetime.now().strftime()and define theactivitystring. - We create a
log_entryby combining thetimestampandactivity. - We open the
log_filein append mode (“a”) and write thelog_entryto the file.
This example demonstrates how to check if a file exists, create it if it doesn’t, and then write data to it.
Read Python file Does Not Exist Exception
Conclusion
In this tutorial, I explained how to check if a file exists and create it if not in Python. I discussed three methods to check if a file exists in Python they are using os.path.exists() method, using os.path.isfile() method, and pathlib.Path.exists() method. I also discussed how to create a file if it does not exist, check if a file exists, and create it if not in Python.
You may also like to read:

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.