How to Write a List To a File in Python – Definitive Guide?

Python lists allow you to store multiple items in a single object.

You can write a list to a file in Python using the file.writelines(your_List_name) method.

Basic Example

colours = ['Orange', 'White', 'Green', 'Blue']

with open('list_of_colours.txt', 'w') as f:

    for colour in colours:

        f.write(colour+ "\n")

This tutorial teaches you how to write a list to file in Python using different methods.

To write a list to a file in Python, you need to open the file using the open() method.

  • The open method accepts a file name parameter and an optional mode parameter.

The different types of modes available to write to a file are:

  • w – Opens the file for writing. Truncates the existing content of the file and writes the new content
  • x – Creates a new file and opens it for writing. The open operation fails if the file with the same name already exists
  • a – Opens the file for writing. It appends the new content at the end of the file
  • b – Opens the file in binary mode. Used to write binary files such as machine learning model file

Using Write Method

The write method writes a string to the file Object.

  1. Open the file in the write mode. (All the contents will be truncated if the file with the same name already exists)
  2. Iterate over the list items using the for loop
  3. Invoke the f.write() method and pass the currently iterated list item. If you would like to write each list item in a new line, then append the new line String \n during each iteration

The list items will be written to the file line by line.

Code

The code below demonstrates how to write a list of colours to the file list_of_colour.txt by opening the file in the write mode.

colours = ['Orange', 'White', 'Green', 'Blue']

with open('list_of_colours.txt', 'w') as f:

    for colour in colours:

        f.write(colour+ "\n")

Output

If you open the file, you’ll see the list of colours (each colour is written on a new line).

Orange
White
Green
Blue

If you want to write the unique items in the list to a file, you can get Get Unique Values From a List in Python and write it to the file.

Using Write and Append Mode

This section teaches you how to use the write() method in the append mode.

To append,

  • open the file in the append mode using the a mode parameter.

While using this method, the list items will be appended to the existing content of the file.

colours = ['Orange', 'White', 'Green', 'Blue']

with open('list_of_colours.txt', 'a') as f:
    for colour in colours:
        f.write(colour+ "\n")

Output

Orange
White
Green
Blue

Orange
White
Green
Blue

Using WriteLines Method

This section teaches you how to use the writelines() method to write a list to the file.

  • This method doesn’t add any line separators. Hence, all the list items are added in a single line.

Similar to the write() method,

  • Open the file in the write mode
  • Invoke the writelines() method to write the list to the file.

Use this method if you want to write a list of items and do not want to iterate through the list of items.

Code

The code below demonstrates how to write a list to a file using the writelines() method.

colours = ['Orange', 'White', 'Green', 'Blue']

with open('list_of_colours.txt', 'w') as f:
    f.writelines(colours)

Output

OrangeWhiteGreenBlue

Writing Line By line Using WriteLines Method

This section teaches you how to use the writelines() method and write each list item in a new line.

  • Use the list comprehension and append the line separator \n to each list item.
  • Pass the list to the writelines() method. Each item will be written in a new line.
colours = ['Orange', 'White', 'Green', 'Blue']

colors = ["{}\n".format(colour) for colour in colours]
with open('list_of_colours.txt', 'w') as f:
    f.writelines(colors)

This is how the writelines() method can be used to write list items to a file without a loop.

Handling Encoding

Encoding represents a set of characters.

You need to use the proper encoding while opening the file, especially when you have special characters like German or Spanish words with tildes(ñ, Ñ).

The utf-8 encoding is commonly used and supports these types of special characters.

The default encoding of Python 3 is utf-8, and it is only extended to byte to String conversions. The open() method in Python uses your environment to choose an environment.

Code

The code below demonstrates how to specify the encoding while opening the file to write special characters into it.

colours = ['Orange', 'White', 'Green', 'Blue','Weiß']

with open('list_of_colours.txt', 'w', encoding='utf-8') as f:
    for colour in colours:
        f.write(colour+ "\n")

Output

Orange
White
Green
Blue
Weiß

This is how you can use encoding to handle special characters in a file.

Using Pickle

The Pickle module is used to serialize and deserialize a Python object structure.

While using Pickle,

  • A binary object file is created. Hence, no specific extension is to be specified while opening the file.
  • You need to open the file in binary mode using the b parameter.

Use the Pickle module to serialize a list into a character stream. This is useful when you are working with machine learning and data science.

Code

The code below demonstrates how to use the Pickle module to serialize a list to a binary file.

import pickle

colours = ['Orange', 'White', 'Green', 'Blue']

with open('listfile', 'wb') as f:
    pickle.dump(colours, f)

Output
The list content is serialized as a binary file.

Äï-]î(åOrangeîåWhiteîåGreenîåBlueîåWei√üîe.

You cannot open the binary file in the Jupyter notebook. You can use any other text editor to view the binary file content.

Additional Resources

Leave a Comment