How to create a file if not exists with Python?

In today’s tutorial we will learn to use Python in order to create empty files (text, csv, excel, json) in our computer file system. There are several ways to accomplish this, we’ll provide a quick rundown of the key topics.

Check if file exist in directory and append

We will typically use the Python standard library open function, which when invoked, creates a new file object. In the first example, we will leverage the capabilities of the pathlib module, introduced in Python 3.4 to add a new file if not available, or alternatively, if the text file exists, the we will append a line of text at the end of it.

from pathlib import Path

# replace with your preferred directory path
f_p = Path(r"C:\WorkDir\new_file.txt")
# check if file is available in the file system
if not f_p.is_file():
    # create the file
    with open(f_p, "w") as f:
        print('Empty text file was just created at {}.'.format(f_p))
else:
    # append to existing file
    with open(f_p, "a") as f:
       f.write('\nThis line will be appended at the end of the text file.')
       print('Text appended to the existing file: {}.'.format(f_p))

Check if file exist with the os Module

Before Python 3.4, we can use the os module. Here’s a simple example in which we create a csv file.

import os

f_p = r"C:\WorkDir\new_file.csv"
# check if file is available in the file system
if not os.path.isfile(f_p):

    with open(f_p, "a") as f:
        print('Empty text file was just created at {}.'.format(f_p))
else:
    with open(f_p, "a") as f:
       f.write('\nThis line will be appended at the end of the text file.')
       print('Text appended to the existing file: {}.'.format(f_p))

Overwrite file if exists

We can override the file if it exist:

from pathlib import Path

# replace with your preferred directory path
f_p = Path(r"C:\WorkDir\new_file.txt")
# check if file is available in the file system
if not f_p.is_file():
    with open(f_p, "w") as f:
        print('Empty text file was just created at {}.'.format(f_p))
else:
    # override existing file
    with open(f_p, "w") as f:
       print('File {} was overwitten.'.format(f_p))

Add folder if not available in file system

In a similar fashion we are able to verify if a directory folder is present in the file system and create it as needed. We’ll use the pathlib mkdir function to add the directory.

from pathlib import Path

# replace with your preferred directory path
dir_path = Path(r"C:\WorkDir1")
           
# check if file is available in the file system
if not dir_path.is_dir():
    # create the file
       dir_path.mkdir()
       print('Folder created at {}.'.format(dir_path))
else:
    print('Folder already exists.')

In Python versions below 3.4 we can use the os module to accomplish a similar outcome:


import os

if os.path.exists (dir_path):
    print('Directory exists')
else:
    os.makedirs(dir_path)
    print('Directory {} created. '.format(dir_path))

Created file or directory and can’t see it on Windows

A common issue that people seem to be encountering on Windows 10 and 11, is that created files and folders are not visible in the File explorer. Typically this is just related to a Windows refresh issue. You can fix this by hitting on F5 or make a right click on the File Explorer dialog and hit refresh.