09-Dec-2022
.
Admin
Hi Dev,
Today, create an multiline text file in python is our main topic. This article goes in detailed on python create new multiline txt file with open. this example will help you python make new multiline text file example. I explained simply about python create a new multiline text file.
There are a few ways to create a new multiline text file in python. we will use open() function and write() function to create text file. I will give you some examples to create new text file with multiple lines in python. so let's see one by one examples.
so let's see following examples with output:
Example 1: 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 2: 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
Example 3: 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 4: 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.
#Python