Use writelines() Function to write multiple lines to file in Python. This function writes several string lines to a text file simultaneously. An iterable object, such as a list, set, tuple, etc., can be sent to the writelines() method.
file.writelines(list)
Python writes multiple lines to file
Simple example code.
with open('file.txt', 'a') as file:
l1 = "Welcome to EyeHunts\n"
l2 = "Write multiple lines\n"
l3 = "Done successfully\n"
l4 = "Thank You!"
file.writelines([l1, l2, l3, l4])
Output:
Other examples
Use the open() function.
with open('data.txt', 'a') as f:
line1 = "PS5 Restock India \n"
line2 = "Xbox Series X Restock India \n"
line3 = "Nintendo Switch Restock India"
f.writelines([line1, line2, line3])
Or
with open('readme.txt', 'w') as f:
line1 = "Hi! \n"
line2 = "This is code\n"
line3 = "Thank you"
f.writelines([line1, line2, line3])
print("New text file created successfully!")
Create a Multiline Text File with a List
myLines = ["Hi!", "This is code", "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!")
Do comment if you have any doubts or suggestions on this Python write file topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.