Categories
Python Answers

How to write a list to a file with Python?

Spread the love

Sometimes, we want to write a list to a file with Python.

In this article, we’ll look at how to write a list to a file with Python.

How to write a list to a file with Python?

To write a list to a file with Python, we can use a loop.

For instance, we write

with open("your_file.txt", "w") as f:
    for item in my_list:
        f.write("%s\n" % item)

to open your_file.txt with open with write permission.

Then we use a for loop to loop through my_list and write the item in the list to the file with f.write.

Conclusion

To write a list to a file with Python, we can use a loop.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *