Create a File if Not Exists in Python

In this tutorial, we will learn some of the different ways to create a file if it doesn't exist in Python.

 

Create a File if it Doesn't Exist in Python Using the open() Function

The open() function can create a file if the path doesn't exist. To do this set the mode to w+.

 

file = open('dir/file.txt', 'w+')

 

Create File if it Doesn't Exist using the touch() Method from the pathlib Package

The touch() method from the Python pathlib package will create a new file only if it doesn't exist when the exist_ok=True argument is supplied. Use it like this:

 

from pathlib import Path

file = Path('dir/file.txt')
file.touch(exist_ok=True)
f = open(file)