How to Create Empty Text File in Python?

08-Dec-2022

.

Admin

How to Create Empty Text File in Python?

Hi Dev,

Now, let's see tutorial of how to create empty text file in python. if you want to see example of python create empty text file in directory then you are a right place. you'll learn how to create empty text file in python. We will look at example of python empty a text file. you will do the following things for python create empty text file in directory.

There are a few ways to create a new empty text file in python. we will use open() function and close() function to create an empty text file. I will give you some examples to create a new empty text file in python. so let's see one by one examples.

so let's see following examples with output:

Example 1: Python Empty Create Text File


main.py

# create new empty text file code

open('readme.txt', 'w').close()

print("New empty text file created successfully!"

Output:

It will create readme.txt file with without text.

Example 2: Python Create Text File

main.py

# create a 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!

Example 3: Python Create Multiline Text File

main.py

# create a new text file with multi lines code

with open('readme.txt', 'w') as f:

line1 = "Hi ItSolutionstuff.com! \n"

line2 = "This is body \n"

line3 = "Thank you"

f.writelines([line1, line2, line3])

print("New text file created successfully!")

Output:

It will create readme.txt file with following text.

Hi ItSolutionstuff.com!

This is body

Thank you

Example 4: Python Create Multiline Text File with List

main.py

myLines = ["Hi ItSolutionstuff.com!", "This is body", "Thank you"]

# create a new text file with multi lines code

with open('readme.txt', 'w') as f:

for line in myLines:

f.write(line)

f.write('\n')

print("New text file created successfully!")

Output:

It will create readme.txt file with following text.

Hi ItSolutionstuff.com!

This is body

Thank you

#Python