In this tutorial, I will explain how to create a file in Python if it doesn’t exist. As a developer working on various projects, I came across a scenario while working on files, where I needed to create a file in Python which do not exist, this made me explore more about creating files. Let us learn more about this topic today.
Create a File in Python if It Doesn’t Exist
Let us learn how to create a file in Python if it doesn’t exist.
Read How to Write JSON Data to a File in Python?
Use the open() Function
The simplest way to create a file if it doesn’t exist is by using the built-in open() function in Python. The open() function allows you to open a file for reading, writing, or appending. When opening a file in write mode (‘w’), Python will automatically create the file if it doesn’t exist.
Here’s an example:
import os
file_path = 'users/john_doe.txt'
# Ensure the directory exists before creating the file
directory = os.path.dirname(file_path)
os.makedirs(directory, exist_ok=True)
with open(file_path, 'w') as file:
file.write('John Doe\n')
print("File created successfully.")Output:
File created successfully.You can look at the output in the screenshot below.

In this code snippet, we specify the file_path as 'users/john_doe.txt'. The open() function is used with the 'w' mode, which opens the file for writing. If the file doesn’t exist, Python will create it. We then use the write() method to write some data to the file.
Check out How to Write a Variable to a File in Python?
Check Directory Existence
To create a file in a directory that may not exist, we can use the os module in Python. The os module provides functions for interacting with the operating system, including file and directory operations.
Here’s an example that checks if the directory exists and creates it if necessary:
import os
directory = 'users'
file_name = 'john_doe.txt'
file_path = os.path.join(directory, file_name)
if not os.path.exists(directory):
os.makedirs(directory)
with open(file_path, 'w') as file:
file.write('John Doe\n')
file.write('New York, USA\n')You can look at the output in the screenshot below.

In this example, we use the os.path.join() function to create the file_path by joining the directory and file_name. We then check if the directory exists using os.path.exists(). If it doesn’t exist, we create it using os.makedirs().
Finally, we open the file using open() with the 'w' mode and write the data to it.
Read How to Copy File and Rename in Python
Append to a File
If you want to append data to a file instead of overwriting its contents, you can use the 'a' mode when opening the Python file. The 'a' mode opens the file for appending, and if the file doesn’t exist, Python will create it.
Here’s an example:
file_path = 'users/jane_smith.txt'
with open(file_path, 'a') as file:
file.write('Jane Smith\n')
file.write('California, USA\n')You can look at the output in the screenshot below.

In this case, if the 'users/jane_smith.txt' file doesn’t exist, Python will create it. If it already exists, the new data will be appended to the end of the file.
Check out How to Get the File Size in MB using Python?
Handle Exceptions
When working with files, it’s important to handle exceptions that may occur. For example, if you try to create a file in a directory where you don’t have write permissions, Python will raise a PermissionError.
Here’s an example that demonstrates exception handling:
try:
file_path = '/restricted/confidential.txt'
with open(file_path, 'w') as file:
file.write('Top Secret Information')
except PermissionError:
print('Permission denied. Unable to create the file.')In this code, we attempt to create a file in a restricted directory. If a PermissionError occurs, we catch it and print an appropriate error message.
Read How to Read Tab-Delimited Files in Python?
Conclusion
In this tutorial, I have explained how to create a file in Python if it doesn’t exist. I discussed how to use the open() function, check directory existence, append to a file, and handle exceptions.
You may like to read:
- How to Read XML Files in Python?
- How to Clear a File in Python?
- How to Write Lines to a File in Python?

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.