Write List To A File In Python

In this tutorial, I will show you how to read and write list to a file in python. Also, how we can read and write to different types of files like text, JSON, binary file. So let’s get started.

1. Write To A Text File

In this section, I will give you two methods for how to read and write the list data to a text file.

Method 1

Here is method 1 of reading and writing the list data from the text file.

Write List To A File In Python

To write data, we first open the text file in the write mode and then iterate through each element of the list and write that each element as the entire line inside the text file.

# Function  to Write List To A File In Python
def write_to_list(array,file_name):

    # Open the file using open() function in writing mode
    with open(file_name,"w") as file:
        # Loop through each element of the list
        for item in array:
            # Write item to the file
            file.write(item+'\n') # append new line to each item


array = ['one','two','three'] # our list
file_name = "database.txt" # file name

write_to_list(array,file_name)

Read Data From The File

To read data from the text file. We first define an empty list, then we open the text file in the read mode and iterate through each line and store it inside the list by skipping a new-line character.

# Function to read data from the file
def read_from_file(file_name):
    data = []

    #Open the file using the open() function in reading mode
    with open(file_name,"r") as file:

        # Loop through each line
        for item in file.readlines():
            # Add data to list by skipping new line char
            data.append(item[:-1]) # Skip last '\n' char

    return data # Return data to the caller

file_name = "database.txt"
data = read_from_file(file_name)
print(data)

Output :

Save and run the above code you should see the following output.

Output of program for write list to a file in python

Method 2

Here is the method 2 of reading and writing the list data to the text file.

Writing Data

To write data, we first concatenate all elements of the list by the predefined separator into a string. Then we write that string to the text file.

# program to write list to a file in python
def write_to_list(array,file_name,separator):
    """
    Function to write to file
    """

    # use join() method on a string to join the data
    # inside the array separated by a separator
    string = separator.join(array)

    with open(file_name,"w") as file:
        # Open the file and write the string as it is
        file.write(string)

array = ['one','two','three'] # our list
file_name = "database.txt" # file name
separator= "|"

write_to_list(array,file_name,separator)

Reading Data

To recover the data, we first read the whole content of the file and store it in a variable then we split the string by a predefined separator that gives us original list data.

# Function to read data from the file
def read_from_file(file_name,separator):
    with open(file_name,"r") as file:
        # read the whole data
        data = file.read()

        # Split the data by a seperator
        data = data.split(separator)

    return data # Return data to the caller

file_name = "database.txt"
separator = "|"
data = read_from_file(file_name,separator)
print(data)

2. Write List To A JSON file

The problem with the text file is that we can’t easily store and recover other data types like integer and floats.

To solve this problem, we can also use JSON files to read and write the list data. Fortunately, python made our job easy by providing a JSON module to work with JSON files.

Write Data

To write data inside the JSON file. We first import the JSON module and then open the JSON file in write mode then dump the input list inside the file.

import json
# import the json module

# Function to write data to a json file
def write_to_list(array,file_name):

    # Open the json file in writing mode
    with open(file_name,"w") as file:

        # Simply write data
        json.dump(array, file)


array = ['one','two',1]
file_name = "database.json" # Now we have json file
write_to_list(array,file_name)

Read Data

Here is the code to read data from the JSON file.

import json

def read_from_file(file_name):
    # Open the json file in reading mode
    with open(file_name,"r") as file:
        data = json.load(file) # Load the data from the file

    return data

file_name = "database.json"
data = read_from_file(file_name)
print(data)

3. Write List To A Binary File

If your list contains other data types like a dictionary, tuple, etc. you have to use the builtin pickle module to read and write to a binary file.

Write Data

To write the list, we first import the pickle module then we open the binary file that having .data extension in the write-binary mode. Later we dump the list inside the file.

import pickle

#Write List To A File In Python
def write_to_list(array,file_name):
    # Open the file in write binary mode
    with open(file_name,"wb") as file:

        # Simply write data
        pickle.dump(array, file)


array = ['one',1,{"two":"three"}]
file_name = "database.data" # Now we have .data file
write_to_list(array,file_name)

Read Data

Here is the code of how to read the list data from the binary file.

import pickle


def read_from_file(file_name):
    # Open the file in read binary mode
    with open(file_name,"rb") as file:
        data = pickle.load(file) # Load the data from the file

    return data

file_name = "database.data"
data = read_from_file(file_name)
print(data)

That’s wrap for the tutorial on how to read and write list to a file in python.

Also, read about how to find factorial in python

Leave a Reply