How to Write a List to a CSV file in Python?

You can use the csv module, the Pandas library or even pure Python code to write a list to a CSV file. This operation will allow you to convert data from one of the most common data types in Python to one of the most used file formats in the world. Which can be useful if you need to send the results of a Python script to an external tool, for instance.

Leverage the built-in CSV module

We can import the CSV module, which comes handy to read and write CSV files to write the items of our list into a CSV file.

We start by creating a list with the elements we we want to write and import the csv module.

#our list items = ['John','Alice','Tom','Esteve'] #import the csv module import csv
Code language: Python (python)

We then use the open() function to create an empty file we’ll use to write our data.

#our list items = ['John','Alice','Tom','Esteve'] #import the csv module import csv #open our file with open('data.csv', 'w', newline='\n'):
Code language: Python (python)

This line creates a file object with associated methods we’ll be using in the rest of our code. The w we use as a second parameter stands for “write”: we open a file with write rights. Other values can be used based on your objective:

CharacterMeaning
'r'open for reading (default)
'w'open for writing, truncating the file first
'x'open for exclusive creation, failing if the file already exists
'a'open for writing, appending to the end of file if it exists
'b'binary mode
't'text mode (default)
'+'open for updating (reading and writing)

We continue with our code and write the items we have in our list to our file:

#our list items = ['John','Alice','Tom','Esteve'] #import the csv module import csv #open our file with open('data.csv', 'w', newline='\n'): #write items writer = csv.writer(f) #use the name of your list here writer.writerows(items)
Code language: Python (python)

This code is simple and almost no dependency, which is why I suggest using it if are not dealing with too much data. Please note that you can use list of lists to create CSV files with more than one data points:

#our list items = [ ['John', 'Teacher',1000], ['Alice', 'Teacher',2000], ['Tom', 'Student',10], ['Esteve', 'Student',100] ] #import the csv module import csv #open our file with open('data.csv', 'w', newline='\n'): #write items writer = csv.writer(f) #use the name of your list here writer.writerows(items)
Code language: Python (python)

Use Pandas

If you are dealing with a lot of data, you may already be using a Pandas DataFrame in your workflow. One of the most useful methods is to_csv() to write your data to a CSV file.

#our list items = [ ['John', 'Teacher',1000], ['Alice', 'Teacher',2000], ['Tom', 'Student',10], ['Esteve', 'Student',100] ] #import the pandas library import pandas as pd #load our data df = pd.DataFrame(items, columns = ['name','role','note']) #write to csv df.to_csv('data.csv')
Code language: Python (python)

This method is powerful because you can custom the export by using some of its parameters. My favorites:

NameFunctionality
sepString of length 1. Field delimiter for the output file.
headerWrite out the column names. If a list of strings is given it is assumed to be aliases for the column names.
indexWrite row names (index).

Write your custom Python code

Python is great because it comes with numerous modules or library that we can use. That being said, we sometimes want to avoid external dependency to increase speed or prevent our code from breaking as a change is applied to a library. In such situation, we’ll want to avoid using pandas or even csv.

The code is very similar to what we created in the first section:

#our list items = ['John','Alice','Tom','Esteve'] # open file with open('data.csv','w') as f: #loop our list for item in items: #write value f.write(str(item)) #newline f.write('\n')
Code language: Python (python)

The main advantage of this approach is that it’s not easy to change the column names, delimiters etc… but it works great as well.

Leave a Reply

Your email address will not be published. Required fields are marked *