Create a File if Not Exists in Python

  1. Python Create File if Not Exists Using the open() Function
  2. Python Create File if Not Exists Using the touch() Method of the pathlib Module

This tutorial will explain various ways of how to create a file if it does not exist in Python. We will look into different modes of the file and explain their function.

We will open a file if it exists; otherwise, we will create the file and add text to it. We can do so through the following method in Python.

Python Create File if Not Exists Using the open() Function

The open() function opens the file in Python, it takes the file path and the mode as input and returns the file object as output.

To create and open a file using the open() function when it does not exist , we need to pass the required file mode as a parameter to the function. The file modes and their properties are explained below.

Mode Description
w Write mode
r Read mode
a Append mode
w+ Create the file if it does not exist and then open it in write mode
r+ Open the file in the read and write mode
a+ Create the file if it does not exist and then open it in append mode

From the file modes explained above, we can pass a+ to add the text to the file or create it first if it does not exist. The w+ mode will truncate the file and then open it in write mode, so if we do not want the file to be truncated, we should use the a+ mode.

The code example below demonstrates how to create a file if it does not exist without truncating it using the open() function in Python.

file = open('myfolder/myfile.txt','a+')

In case we want to truncate the file, we can use the following example code:

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

Python Create File if Not Exists Using the touch() Method of the pathlib Module

The path.touch() method of the pathlib module creates the file at the path specified in the path of path.touch(). If we set the exist_ok as True, the function will do nothing if the file exists.

The code example below shows how to use the touch() file to check if the file exists and create it if it does not exist.

from pathlib import Path

myfile = Path('myfolder/myfile.txt')
myfile.touch(exist_ok=True)
f = open(myfile)
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python File

  • Read a Text File Into a List in Python
  • Python Get Filename Without Extension From Path