How to Generate Text File from List in Python?

16-Dec-2022

.

Admin

How to Generate Text File from List in Python?

Hi Dev,

Here, I will show you how to generate text file from list in python. we will help you to give example of python append text file to list. step by step explain python add text file to list. you will learn python write text file from list.

In this example, we will create "myLines" list with some content. Then we will use for loop and add one by one line to the text file. so let's see a below simple example:

Example :


main.py

myLines = ["Hi nicesnippets.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 nicesnippets.com

This is body

Thank you!

#Python