Searching how to write list to file in python? Writing a list of items to a file is a common programming task.

Python provides file operations like reading and writing to files. Writing to files can be done one item at a time, or multiple items all at once.

For example, multiple items in question might be contained in a list data structure. If you want to know how to write list to file in python, you have come to the right place. This tutorial is all about that.

We will be using various approaches to write items contained in a list into a file.

The Dataset to be written in a file

Our dataset will be a collection of information about movies. Each data item in our list is a tuple consisting of the movie name, the movie genre, running time (in minutes), and its rating.


movie_dataset = [("Dune", "Action", 155, 8.1), ("Free Guy", "Comedy", 115, 7.2),
        ("Aadhaar", "Drama", 107, 6.8), ("Master Ji Gong", "Fantasy", 93, 6.5),
        ("Knights of Valor", "History", 80, 5.0), ("Red Rocket", "Drama", 130, 7.2),
        ("Sherni", "Action", 131, 6.8), ("Eternals", "Fantasy", 156, 6.4)]

We will be trying to write this dataset to a text file called movies.txt.

Write list to file using file.write() and a for-loop

Our first attempt will be to iterate over the movie_dataset and write each element to text file using write().


with open("movies.txt", "w") as f:
    # iterate over items in list, and write each to file
    for movie in movie_dataset:
        value = str(movie)[1:-1]
        f.write(value + '\n')

For each item, we needed to make a conversion to string since write() expects a string as an argument, not a tuple.

Also, we don’t want to write the parenthesis of each tuple string, that is why we needed to strip the open and close parenthesis from each movie string.

Finally, we appended a newline to separate each value in the file.

To see the result of our efforts, we can run the following code


# read back and print
with open("movies.txt", "r") as f:
    print(f.readlines())

This gives us the following output:

["'Dune', 'Action', 155, 8.1\n", "'Free Guy', 'Comedy', 115, 7.2\n", "'Aadhaar', 'Drama', 107, 6.8\n", "'Master Ji Gong', 'Fantasy', 93, 6.5\n", "'Knights of Valor', 'History', 80, 5.0\n", "'Red Rocket', 'Drama', 130, 7.2\n", "'Sherni', 'Action', 131, 6.8\n", "'Eternals', 'Fantasy', 156, 6.4\n"]

From our printout, we see that the file is made up of a list of lines, each ending with a newline.

Write list to a file, but unpack the tuples first

In the previous example, we had to convert each tuple into a string and express it in a way to make it suitable to be written to the file. We could still follow another approach to make the tuple a neat line that is easily readable from the file later.

Here, we will have to unpack the tuple and construct a string that can be written to the file.


with open("movies.txt", "w") as f:
    # iterate over items in list, and write each to file
    for name, genre, running_time, rating in movie_dataset:
        value = f"{name},{genre},{running_time},{rating}"
        f.write(value + '\n')

Run the file reading code to view the contents of the file


# read back and print
with open("movies.txt", "r") as f:
    print(f.readlines())
['Dune,Action,155,8.1\n', 'Free Guy,Comedy,115,7.2\n', 'Aadhaar,Drama,107,6.8\n', 'Master Ji Gong,Fantasy,93,6.5\n', 'Knights of Valor,History,80,5.0\n', 'Red Rocket,Drama,130,7.2\n', 'Sherni,Action,131,6.8\n', 'Eternals,Fantasy,156,6.4\n']

Our code was successful here also. Though there were no spaces in the lines, unlike the previous code example.

So far, we have been using the write() method of the file object. the next two examples will make use of writelines() method of the file object.

Write list to file by writing a single string to the file

The writelines() method takes a list argument and writes its contents to a file. The next example will attempt to do this by first converting the list of tuples into a list of strings, before writing.


with open("movies.txt", "w") as f:
    movie_dataset_strings = [(str(movie)[1:-1] + '\n') for movie in movie_dataset]
    f.writelines(movie_dataset_strings)
    

We converted the movie dataset from a list of tuples into a list of strings by making use of a list comprehension.

Each item in the list comprehension has the form str(movie)[1:-1] + '\n'. We gave it the form because we needed to strip out the parentheses from the tuple, then add a newline as a separator for each item. This will make it easier to read the items, line by line later.

To see that we succeeded, we will run the following code.


# read back and print
with open("movies.txt", "r") as f:
    print(f.readlines())

Our output is similar to the one we got from the first example

["'Dune', 'Action', 155, 8.1\n", "'Free Guy', 'Comedy', 115, 7.2\n", "'Aadhaar', 'Drama', 107, 6.8\n", "'Master Ji Gong', 'Fantasy', 93, 6.5\n", "'Knights of Valor', 'History', 80, 5.0\n", "'Red Rocket', 'Drama', 130, 7.2\n", "'Sherni', 'Action', 131, 6.8\n", "'Eternals', 'Fantasy', 156, 6.4\n"]

Write to file by unpacking the tuples, and using writelines()


with open("movies.txt", "w") as f:
    movie_dataset_strings = [f"{name},{genre},{running_time},{rating}\n" 
                                for (name, genre, running_time, rating) in movie_dataset]

    f.writelines("".join(movie_dataset_strings))

Run the file reading code to view the contents of the file


# read back and print
with open("movies.txt", "r") as f:
    print(f.readlines())
['Dune,Action,155,8.1\n', 'Free Guy,Comedy,115,7.2\n', 'Aadhaar,Drama,107,6.8\n', 'Master Ji Gong,Fantasy,93,6.5\n', 'Knights of Valor,History,80,5.0\n', 'Red Rocket,Drama,130,7.2\n', 'Sherni,Action,131,6.8\n', 'Eternals,Fantasy,156,6.4\n']

Write list to csv file

In the previous examples, we have been writing to text files. It is also possible to write to CSV files in python. To do this, we need to import python’s csv module. This module contains the writer class which we can use to carry out writing to a csv file. The following code shows just how we can do this.


from csv import writer

# write the movie dataset to the csv file

# open the file for writing
with open('movies.csv', 'w') as f:
    # create the csv writer from the file object
    writer = writer(f)

    # write all the rows of movies to the csv file
    writer.writerows(movie_dataset)

The csv file produced (‘movies.csv’) has empty lines in between each movie data row

Output:

Dune,Action,155,8.1

Free Guy,Comedy,115,7.2

Aadhaar,Drama,107,6.8

Master Ji Gong,Fantasy,93,6.5

Knights of Valor,History,80,5.0

Red Rocket,Drama,130,7.2

Sherni,Action,131,6.8

Eternals,Fantasy,156,6.4

In order to avoid printing blank lines between each row, we will have to pass an empty string to the newline argument of the file open() function. This will suppress the production of the extra newline that is causing the blank lines under each data row.


from csv import writer

# write the movie dataset to the csv file

# open the file for writing
with open('movies.csv', 'w', newline='') as f:
    # create the csv writer from the file object
    writer = writer(f)

    # write all the rows of movies to the csv file
    writer.writerows(movie_dataset)

Output:

Dune,Action,155,8.1
Free Guy,Comedy,115,7.2
Aadhaar,Drama,107,6.8
Master Ji Gong,Fantasy,93,6.5
Knights of Valor,History,80,5.0
Red Rocket,Drama,130,7.2
Sherni,Action,131,6.8
Eternals,Fantasy,156,6.4

Conclusion

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

Thanks for reading the tutorial, and please check out our other tutorials on the python programming language.

Want to help with python homework for more such awesome python projects?  Feel free to contact us.

Like this article? Follow us on Facebook and LinkedIn.