How to Check If a File Exists and Create It If Not in Python?

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.

Check If a File Exists and Create It If Not in Python

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.

How to Check If a File Exists and Create It If Not in Python

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.

Check If a File Exists and Create It If Not in Python pathlib.Path.exists()

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.

Create a File If It Doesn't Exist

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:

  1. We import the necessary modules: os for file and directory operations and datetime for timestamp generation.
  2. We define the log_directory and log_file variables to specify the directory and file name for the log file.
  3. We use os.path.join() to create the full log_path by combining the log_directory and log_file.
  4. We check if the log_directory exists using os.path.exists(). If it doesn’t, we create it using os.makedirs().
  5. We check if the log_file exists using os.path.isfile(). If it doesn’t, we create it using open() with the “w” mode and write the initial header.
  6. We generate a timestamp using datetime.now().strftime() and define the activity string.
  7. We create a log_entry by combining the timestamp and activity.
  8. We open the log_file in append mode (“a”) and write the log_entry to 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:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.