GeekBits

Python Check File Exists and Create It

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.

2 min read
Python Check File Exists and Create It

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.

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.

Sign up for our newsletter

Don't miss anything. Get all the latest posts delivered to your inbox. No spam!