Python Create Text File If Not Exists Example

By Hardik Savani October 30, 2023 Category : Python

Hey Guys,

Today, I would like to show you python create text file if not exists. I explained simply step by step python create text file if it doesn't exist. This example will help you python create file if none exists. you can understand a concept of python create a file if not exist. you will do the following things for how to create text file if not exists python 3.

We will use "w+" parameter in "open()" function to create text file if not exists. Without any further ado, let's see below code example.

You can use these examples with python3 (Python 3) version.

Example 1:

# create new text file code
with open("readme.txt", 'w+') as f:
    f.write('New text file content line!')
print("New text file created successfully!")


It will create readme.txt file with following text.

New text file content line!

I hope it can help you...

Tags :