To write a list to a file, python provides several ways. List in python is used to store data that Is accessible during the program execution whereas files can be used to store data into the disc.
Sometimes when we want to store some programmatic data for persistent purposes then we need to store the list in a file.
In this article, we will learn to write list data to a file by using these methods:
file.write() Method
numpy.savetxt() Method
pickle.dump() Method
So, let's get started.
The simplest solution is to use file.write() method that will write all the data of the list to a file. We must open the file in write mode by using 'w' in the open() method. See the Python code below.
"""
Write a list to a file in Python
"""
# Take a list
list1 = [12, 56, 23, 488]
with open('abc.txt', 'w') as f:
for item in list1:
f.write("%s " % item)
print("File has written")
File Output:
12 56 23 488
If you are working with NumPy and want to store a list of elements in a file then use np.savetxt() method that will store all the data. You must specify other arguments as well in the savetxt() method such as delimiter and format of data.
import numpy as np
"""
Write a list to a file in Python
"""
# Take a list
list1 = [12, 56, 213, 488]
np.savetxt('abc.txt', list1, delimiter="\n", fmt="%s")
print("File has written")
File Output:
12
56
213
488
We can also use the print() method with * for argument unpacking and pass the file object to it. It will store/write all the list data to a file. See the Python code below.
"""
Write a list to a file in Python
"""
# Take a list
list1 = [12, 56, 213, 488]
with open("abc.txt", "w") as fout:
print(*list1, sep="\n", file=fout)
print("File has written")
File Output:
12
56
213
488
We can use the join() method to join all the list elements into a single one and then write to a file by using the file.write() method.
"""
Write a list to a file in Python
"""
# Take a list
list1 = ["my","favourite","book","is","alchemist"]
with open("abc.txt", "w") as file:
file.write("\n".join(list1))
print("File has written")
File Output:
my
favourite
book
is
alchemist
If you are working with pickle then use its dump() method to write a list to a file. You can use it to serialize a list to disk for later use.
import pickle
"""
Write a list to a file in Python
"""
# Take a list
list1 = ["my","favourite","book","is","alchemist"]
with open('abc.txt', 'wb') as fp:
pickle.dump(list1, fp)
print("File has written")
We can also use json.dumps() method to pass list data to write() method and then the write() method writes all the data to a file. See the Python code.
import json
"""
Write a list to a file in Python
"""
# Take a list
list1 = ["my","favourite","book","is","alchemist"]
with open('abc.txt', 'w') as f:
f.write(json.dumps(list1))
print("File has written")
File Output:
["my", "favourite", "book", "is", "alchemist"]