How to Create a File If It Doesn’t Exist in Python?


Creating a file in Python is relatively simple, but what if the file you want to create doesn’t exist?

In this blog post, we’ll show you how to create a file if it doesn’t exist using Python.

Keep reading to learn more!

First, let’s take a look at the os.path module. This module provides us with many useful functions that make working with files and directories much easier.

One such function is os.path.exists(). This function returns True if the given path exists and False if it doesn’t.

Armed with this knowledge, we can now write a simple script to create a file if it doesn’t exist:

import os file_name = 'file_test.txt' if not os.path.exists(file_name): open(file_name, 'w').close() print('The File created successfully')
Code language: JavaScript (javascript)

Let’s break down this code so that we can understand what’s happening:

  • We start by importing the os module. This module provides us with many useful functions for working with files and directories.
  • Next, we create a variable called filename and set it equal to ‘file_test.txt’. This is the name of the file that we want to create.
  • Then, we use the os.path.exists() function to check if the file already exists or not. If the file exists, this function will return True; if it doesn’t exist, it will return False.
  • If the file doesn’t exist (i.e., if the function returns False), we use the open() function to create it. We then close the file immediately after creating it so that we don’t leave it open unnecessarily. Once the file has been created (or if it already existed), we print a message to let us know that everything went as planned.
  • That’s all there is to it! With just a few lines of code, we were able to create a new file if it didn’t already exist using Python.

another python script to create a file

import os.path if not os.path.isfile("myfile.txt"): f = open("myfile.txt", "w") print('The File created successfully') else: print("The File already exists")
Code language: PHP (php)

Creating a new file in Python is a relatively simple task but, as you can see from this blog post, there are a few things you need to keep in mind when doing so.

In particular, you need to import the os module and use the os.path.exists() function to check if the file you want to create already exists or not before actually creating it with the open() function.

Keep these things in mind next time you need to create a new file in Python and you should be good to go!

Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts