Writing a List to a File in Python — A Step-by-Step Guide

Writing a list to a file in Python

In Python, a list is a common data type for storing multiple values in the same place for easy access.

These values could be numbers, strings, or objects.

Sometimes, it’s useful to write the contents of a list to an external file.

To write a Python list to a file:

  1. Open a new file.
  2. Separate the list of strings by a new line.
  3. Add the result to a text file.

Here is an example code that shows how to do it:

names = ["Alice", "Bob", "Charlie"]

with open("example.txt", mode="w") as file:
    file.write("\n".join(names))

As a result, you should see a text file with the names separated by a line break.

Alice
Bob
Charlie

Obviously, this is only one approach. If you are not satisfied with it, see the other examples below.

Write List to File As-Is

You cannot directly write a list to a file. But you can convert the list to a string, and then write it.

For example:

names = ["Alice", "Bob", "Charlie"]

with open("example.txt", mode="w") as file:
    file.write(str(names))

As a result, you see a text file called example.txt with the following contents:

['Alice', 'Bob', 'Charlie']

Write List to File Comma-Separated without Brackets

To write a list into a text file with comma-separated values without brackets, use string.join() method.

For example:

names = ["Alice", "Bob", "Charlie"]

with open("example.txt", mode="w") as file:
    file.write(", ".join(names))

As a result, you see a text file called example.txt with the following contents:

Alice, Bob, Charlie

Write Python List to File Tab-Delimited

Sometimes you might want to write the list contents into an external file by using tabs as separators between the values.

To do this, you need to use the string.join() method to join the list elements by using a tab as a separator.

For example:

names = ["Alice", "Bob", "Charlie"]

with open("example.txt", mode="w") as file:
    file.write("\t".join(names))

The result is a file called example.txt with the following contents tab-separated:

Alice	Bob	Charlie

Conclusion

Today you learned how to write a list to a file in Python.

To recap, all you need to do is open a file, separate the strings, and write them into the file. All this happens by using the native methods in Python in a couple of lines of code.

Thanks for reading. I hope you enjoy it.

Scroll to Top