Create Text File in Python Example

07-Dec-2022

.

Admin

Create Text File in Python Example

Hi Dev,

If you need to see example of create text file in python example. if you have question about python create new text file with open then I will give simple example with solution. We will use python make new text file example. you'll learn python create a new text file. follow bellow step for python create text file example.

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

so let's see following examples with output:

Example 1: 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 2: 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 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