How to Create Not Exists Text File in Python?

15-Dec-2022

.

Admin

How to Create Not Exists Text File in Python?

Hi Dev,

In this tute, we will discuss how to create not exists text file in python. We will use how to create text file if not exists python. I would like to share with you python create a file if not exist. This article will give you simple example of python create file if none exists.

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.

so let's see following examples with output:

Example :


main.py

# 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!")

Output:

It will create readme.txt file with following text.

New text file content line!

#Python