Writing a List to a File in Python

[toc]

Problem Statement: How to write a list to a file with Python?

Mostly Python programmers use persistent storage systems like databases or files to store serialized data structures like arrays, lists, and dictionaries. It is because databases and files are reusable, i.e. after analyzing the given data, we can store it in the file, and later that data can be read to use in an application. There are many different ways to write a list to the file in Python. Let’s look at some of them:

Method 1- Using Read And Write

Python facilitates us with standard methods used to read the data from the file and to write the data to a file. While dealing with single lines, we can use the read() and write() methods, respectively. Suppose we have the following list of strings and we have to store each string in a file using Python:

colors = ["red", "black", "white", "yellow", "blue"]

To write the list in to file, we have to follow the steps given below:

  • Firstly, open the file in write mode by passing the file path and access mode “w” to the open() function.
  • Next, we have to use the “for” loop to iterate the list. In each iteration, we will get a list item that we need to write in the file using the write() method.
  • Β After iterating through the whole list, we need to ensure that we have closed the file. For that, we use the close() method.

Let’s visualize the above demonstration with the help of the following snippet:

# List of colours
colors = ["red", "black", "white", "yellow", "blue"]
# Opening the file in write mode
file = open('colors.txt', 'w')
# Writing the list to the file
for color in colors:
    file.write(color + '\n')
# Closing the file
file.close()

Output:

red
black
white
yellow
blue

Note: The ‘\n‘ character is used for a new line at the end of each item in the list.

Let’s have a look at a situation that demonstrates how we can read the list from the file:

Example:

# Empty list that will read from the file
colors = []
# Opening the file in read mode
with open(r'colors.txt', 'r') as file:
    for color in file:
        x = color[:-1]
        colors.append(x)
print(colors)

Output:

["red", "black", "white", "yellow", "blue"]

Recommended Read: How to Read a File Line-By-Line and Store Into a List?

Method 2- Using Writelines() Method

While dealing with multiple lines, we have to use the readlines() and writelines() file methods in Python.Β  Hence we can write the entire list into a file using the writelines() method.

Example:

# List of colours
colors = ["red", "black", "white", "yellow", "blue"]
# Opening the file in write mode
with open('colors.txt', 'w') as file:
    # Writing the entire list to the file
    file.writelines("\n" % color for color in colors)

Output:

red
black
white
yellow
blue

β¦Ώ The following example shows how to use readlines() to read the entire list from a file in Python:

Example:

# Empty list that will read from the file
colors = []
# Opening the file in read mode
with open(r'colors.txt', 'r') as file:
    colors = [color.rstrip() for color in file.readlines()]

Output:

["red", "black", "white", "yellow", "blue"]

Method 3- Using The Pickle Module

Pickle is a module in Python that is used to serialize or de-serialize an object structure. We can use this module to serialize a list for later use in the same file.Β  The dump() method from the module is used to write the list into a file and it takes the reference of the file and list as its parameters. The method stores the list efficiently as a binary data stream. As it uses a binary stream, the file can even be opened in binary writing mode (wb).Β  Using the module, we can convert any object like a list or dictionary into a character stream. The character stream has the information to reconstruct the object in the future.

Approach: To write a list into the file, we have to first import the pickle module at the start of the program. Then we will use the access mode to open the file. The open() function checks if the file exists or not and if it exists, it gets truncated. The function creates a new one if the file doesn’t already exist. Further, the dump() method converts the object and writes it into the file.

Example:

# Importing the pickle module
import pickle
# Writing the list to the binary file
def writel(a):
    # Storing the list in binary file (wb) mode
    with open('file', 'wb') as fp:
        pickle.dump(colors, fp)
        print('Completed the process of writing the list into a binary file')
# Reading the list to memory
def readl():
    # Reading the list in binary file (rb) mode
    with open('sample', 'rb') as fp:
        n = pickle.load(fp)
        return n
# List of colors
colors = ["red", "black", "white", "yellow", "blue"]
# Calling the writel method
writel(colors)
color = readl()
# Printing the list
print(color)

Output:

Completed the process of writing the list into a binary file
["red", "black", "white", "yellow", "blue"]

Method 4- Using The Json Module

We can use the JSON module to convert the list into a JSON format and then write it into a file using the JSON dump() method. Generally, when we execute a GET request, we will receive a response in JSON format. We can then store the JSON response in a file for any future use.

# Importing the JSON module
import JSON
def writel(a):
    with open("colors.json", "w") as fp:
        json.dump(a, fp)
        print('Completed the process of writing json data into  json file')
# Reading the list to memory
def readl():
    with open('colors.json', 'rb') as fp:
        n = json.load(fp)
        return n
# List of colors
colors = ["red", "black", "white", "yellow", "blue"]
writel(colors)
color = readl()
# Printing the list
print(color)

Output:

Completed the process of writing json data into  json file
["red", "black", "white", "yellow", "blue"]

Conclusion

That’s all about how to write a list to a file with Python. I hope you found it helpful. Please stay tuned and subscribe for more interesting articles. Happy learning!

Recommended: Correct Way to Write line To File in Python

Authors: Rashi Agarwal and Shubham Sayon