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 open the file with open
.
Then we loop through the list items with a for loop and call f.write
on each item.
For instance, we write:
my_list = [1, 2, 3]
with open('your_file.txt', 'w') as f:
for item in my_list:
f.write("%s\n" % item)
We call open
with the path to the text file we want to write to.
'w'
lets us write to the file.
Then we loop through my_list
and call f.write
in the loop body.
Therefore, your_file.txt
has:
1
2
3
as its content.
Conclusion
To write a list to a file with Python, we can open the file with open
.
Then we loop through the list items with a for loop and call f.write
on each item.