How to Create Text File If Not Exists in Python?

Published On: 22/12/2022 | Category: Python


Hi Guys,

This post will give you example of create text file if not exists. you will learn python create file if none exists. you will learn python create a file if not exist. you will learn how to create text file if not exists python 3. Let's see bellow example python create text file if it doesn't exist.

If there isn't a text file, we'll use the "w+" parameter in the "open()" function to create one. Let's look at the code example below without further ado.

So let's see bellow example:

Example 1

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
New text file content line!

It will help you....

Happy Pythonic Coding!