Python Write a List to File with Examples

Writing to files is essential in any programming language, including Python. Often we find ourselves in situations where we would need to write a list into a file. There are multiple approaches to writing a list to file in Python.

Writing a list to file in Python consists of 5 steps regardless of the approach we take:

  1. Define your list
  2. Open the file you want to write to
  3. Iterate over elements in the list
  4. Write element to file
  5. Close file

Also, as already said, we can choose over multiple approaches:

  • write method
  • writelines method
  • json module
  • pickle module

First, let’s see how to use the write method.

Write a list to the file using the write method

The write and writelines methods belong to the TextIOWrapper class. This class is initialized when the open() function is called. TextIOWrapper class is used for reading and writing files in Python.

Let’s see the following example:

books = ["Romeo and Juliet", "Macbeth", "Hamlet"] 
file = open("file.txt", "w")
for book in books:
    file.write(book + "\n")
file.close()

Our file is saved in the same directory as our script, and its output is:

$ cat file.txt
Romeo and Juliet
Macbeth
Hamlet

Although this works, there is a better way to write a list to a file. In the example above, if the error appears, the file remains open, and that’s not entirely safe behavior.

There are two other approaches to the problem mentioned above:

  • Try-catch block
  • With open statement

Using try-catch block, our above example would look like this:

try:
   file = open("file.txt", "w")

   books = ["Romeo and Juliet", "Macbeth", "Hamlet"]
   for book in books:
       file.write(book + "\n")
finally:
   file.close()

This assures that we will successfully close the file even if the error appears. Even though this approach is better than the first one, Python supports closing files without explicitly calling the close() method.

This approach implies using “with statement”. “With statement” is the practice of opening files in Python. We can use Python syntax to open a file, and Python will close it safely without the need for our implementation.

Let’s look at how to use “with statement” when writing a list to a file in Python.

with open('file.txt', "w") as file:
    books = ["Romeo and Juliet", "Macbeth", "Hamlet"]
    for book in books:
        file.write(book + "\n")

This is the best way to use Python to write a list to a file.

WARNING - try-catch and “with statements” are not equivalent. Using with statement is a better and safer approach.

Write a list to the file using the writelines method

The writelines method belongs to the already mentioned TextIOWrapper class. The writelines method, unlike the write method, receives a whole list. The given list is written to a file without formatting and in a single line. That can, of course, be manipulated and changed.

with open('file.txt', "w") as file:
   books = ["Romeo and Juliet", "Macbeth", "Hamlet"]
   file.writelines(books)

But if we see our output, it looks like this:

$ cat file.txt
Romeo and JulietMacbethHamlet

This can be easily changed using the .join method, as seen in the following example:

with open('file.txt', "w") as file:
   books = ["Romeo and Juliet", "Macbeth", "Hamlet"]
   file.writelines('\n'.join(books))

Finally, we get our output formatted:

$ cat file.txt
Romeo and Juliet
Macbeth
Hamlet

Write a list to the file using the json module

The json module is a very known module in the Python community. It helps us use JSON data format (similar to the dictionary in Python). But it also has support for writing to files. So how can we make use of that?

The json module has a dump method that serializes the objects to files.

Usage of json.dump method can be seen in the following example:

import json

with open('file.txt', 'w') as file:
   books = ["Romeo and Juliet", "Macbeth", "Hamlet"]
   json.dump(books, file)

Our output looks somewhat different from other methods:

$ cat file.txt
["Romeo and Juliet", "Macbeth", "Hamlet"]

Our list was written to file in the same format we gave it to the dump method.

Last but not least, we can use the pickle module to write a list to a file in Python.

Write a list to the file using the pickle module

The pickle module is a standard python module used for the serialization of objects. Also, this module has support for file reading and writing.

Here, we’ll focus on the dump() method. However, you can find other methods in the pickle module.

import pickle

with open('file.txt', 'wb') as file:
    books = ["Romeo and Juliet", "Macbeth", "Hamlet"]
    pickle.dump(books, file)

You can see little change from previous examples. We use ‘wb’ in the open function, which means we are writing binary data into a file.

Why is that? 
Dump works with binary data, and only like that data can be written to a file. Even though this data is not humanly readable, we can use it when we need to read the list from a file. Pickle added support for reading binary files and loading them into the list:

with open('file.txt', 'rb') as file:
   books = pickle.load(file)

This method loaded our books list from the above example into the books variable.

Conclusion

I would use TextIOWrapper methods to write a list to file in Python, as it doesn’t require any imports of other modules to a file. But, considering that there are a lot of marginal cases and not every method is best for everything. I hope this article helped you find the right one.