Development

Create a File if Not Exists in Python

Captain Salem 2 min read

Create a File if Not Exists in Python

File operations is one of the most fundamental operations for any programmer. However, it is important to check whether the file you wish to read or write to exists before performing any task. This is because it can lead to an error and force the program execution to break.

In this tutorial, we will explore the various ways to check if a file exists and, if it doesn’t, how to create it. Although Python offers several methods for this, we will mainly focus on two main methods.

Requirements

  1. Basic understanding of Python.
  2. Python 3.11 and higher installed on your system.

Method 1 - Using the os Module

As you can probably guess, the os module is one we can use to perform this task. The module is part of the Python standard library making it an efficient choice for quick error handling during file operations.

We can create a program that checks if a target file exists and creates if not.

import os

# define function
def create_file(filename):
    
    if not os.path.isfile(filename):
        open(filename, 'w').close()
        print(f"File '{filename}' has been created.")
    else:
        print(f"File '{filename}' already exists.")

# Use the function
create_file('sample.txt')

In the example code above, we use the os.path.isfile(filename) to check if the file exists. This function returns True if it does, and False otherwise.

If the file doesn’t exist, we open the file in write mode ('w'), which creates the file.

And finally, we call the close() function to close the file, which frees up system resources.

Using the pathlib Module

In Python 3.4 and higher, we got introduced to the pathlib module which provides an OOP approach to handling filesystem paths. We can use this feature to check whether a file exists and create if otherwise as shown.

from pathlib import Path

# define func
def create_file(filename):
    file = Path(filename)
    
    if not file.is_file():
        file.touch()
        print(f"File '{filename}' has been created.")
    else:
        print(f"File '{filename}' already exists.")
# Use the function
create_file('sample.txt')

Here, we create a Path object with the filename. The is_file() method checks if the file exists, and the touch() method creates the file if it doesn’t.

One advantage of using pathlib over os is that pathlib methods can be chained, leading to more concise code.

Conclusion

In this tutorial, we covered how to create a file in Python if it doesn’t already exist. We went through two methods using the os and pathlib modules.

Share
Comments
More from Cloudenv

Cloudenv

Developer Tips, Tricks and Tutorials.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to Cloudenv.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.