ItSolutionStuff.com

Python Create Text File If Not Exists Example

By Hardik Savani • October 30, 2023
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:

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!

I hope it can help you...

Tags: Python
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Create Multiline Text File in Python?

Read Now →

Python Create an Empty Text File Example

Read Now →

How to Create Text File in Python?

Read Now →

Python String Convert to Uppercase Example

Read Now →

How to Find Average of List in Python?

Read Now →

Python Split String into List of Characters Example

Read Now →

How to Convert String into List in Python?

Read Now →

How to Get Unique Elements from List in Python?

Read Now →

Python Post Request with Json File Example

Read Now →

Python Copy File From one Directory to Another Example

Read Now →

Python Get First Date of Last Month Example

Read Now →

Python Create Zip Archive from Directory Example

Read Now →

Python Subtract Minutes from DateTime Example

Read Now →