How to write Python lists to files with newlines?

In this quick tutorial we will learn how you can export the contents of a Python list object into a text or csv file, while saving each list element into a new line in your file.

We’ll start by defining a very simple list object that we’ll use in the different examples of this tutorial.

lang_lst = ['Python', 'Julia', 'R', 'Haskell']

Save a list to a text file with newlines

We’ll first go ahead and create a text file.

from pathlib import Path

# your file here
f_path = Path(r"C:\WorkDir\lang_file.txt")

Then open the text file in write mode, loop through the list, and write each element. The trick here is to use the f-string formatting (available starting python 3.6) to bring toghether the list element and the \n new line character.

# using string formatting
with open (f_path ,'w') as f:
       for lang in lang_lst:

The list elements will be written without the brackets:


In Python versions that are older than 3.5, we can use the following syntax to export our list to a file object:

f_path = r"C:\WorkDir\my_file.txt"

with open (f_path ,'w') as f:
       for lang in lang_lst:

Export your list contents as pickle

If you are looking to store your list as a text file to persist its content, you might want to consider serializing it to a pickle file.

Writing list to pickle object

In a nutshell you can write your list to pickle in the following way:

import pickle
p_path = r'C:\\WorkDir\\lang_list.pkl'

with open (p_path, 'wb') as pick_object:
    pickle.dump(lang_lst, pick_object)

Reading from pickle file to list

lang_lst_unp = []
with open (p_path,'rb') as pick: