7 ways to write List to CSV in Python

In this post, we are going to learn 7 ways to write List to CSV in Python with the help of the Python code examples using the built-in CSV module.

1. Write list of lists to CSV with header


In the Python program code, we have imported the CSV library using code import CSV and two lists.

  • List_rows : It contains nested list to write to CSV file rows.
  • List_columns: To write first row that is columns or header.

The open(‘animal.csv’, ‘w’) method is used to open the CSV file in write mode. The writer() method is used to write a single row or writerows() for multiple rows.

Python Program code

import csv 
List_columns = ['Name', 'Age', 'Weight', 'City']  
List_rows = [ ['Tom', 9, 8, 'WA'],  ['Trex', 6, 15, 'CA'],  ['Kity', 7, 11, 'WA']] 
with open('animal.csv', 'w') as csvfile: 
    write = csv.writer(csvfile) 
    write.writerow(List_columns) 
    write.writerows(List_rows) 

Output

Name	Age	Weight	City
			
Tom	    9	8	  WA
			
Trex	6	15	CA
			
Kity	7	11	WA

2. Write list to CSV in Python


In this Python program, instead of writing multiple rows to the CSV file at once, we are writing a new Row per list with a header.

  • List_columns: to write the first row that is columns or header.

Python Program

import csv
List_columns = ['Name', 'Age', 'Weight', 'City']
with open('animal.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(List_columns)
    writer.writerow(['Tom', 9, 8, 'WA'])
    writer.writerow( ['Trex', 6, 15, 'CA'])
    writer.writerow(['Kity', 7, 11, 'WA'])

Output

Name,Age,Weight,City
Tom,9,8,WA
Trex,6,15,CA
Kity,7,11,WA

3. Write List of tuples to CSV Python


In this Python program, we are using the CSV module with code import CSV.

The open(‘animal.csv’, ‘w’) method is used to open the CSV file in write mode. The writerow() to write header row or columns of CSV.

  • List_rows : It contain a list of tuples will be written to CSV file rows
  • List_columns: to write first row that is columns or header.

We are using for loop to iterate over each list of tuples and writing a row to CSV file using writerow() method.

Python Program

import csv


List_rows  =[ ('Tom', 9, 8, 'WA'),  ('Trex', 6, 15, 'CA'),  ('Kity', 7, 11, 'WA')]
List_columns = ['Name', 'Age', 'Weight', 'City'] 


with open('animal.csv', 'w') as csvfile: 
    write = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n') 
    write.writerow(List_columns)
    for row in List_rows:
        write.writerow(row)

Output

Name	Age	Weight	City
Tom	9	8	WA
Trex	6	15	CA
Kity	7	11	WA


4. Write list to CSV column in Python


In this Python program example, we have imported the two modules.

  • import csv
  • from itertools import zip_longest :The zip_longest() method is used to make iterator by aggregate element of each iterable and print in sequence and missing in any ietrable padded with fillvalue.

The open(‘animal.csv’, ‘w’) method to open the CSV file in write mode. The writerow() to write header row or columns of CSV.

Python Program

import csv
from itertools import zip_longest

List_columns = ['Name', 'Age', 'Weight', 'City'] 
list_Val= ['Tom', 9, 8, 'WA']

data = [List_columns, list_Val]

zip_data = zip_longest(*data, fillvalue = '')

with open('animal.csv', 'w',encoding="ISO-8859-1", newline='') as csvfile:
         writer = csv.writer(csvfile)
         writer.writerow(("List_columns", "list_Val"))
         writer.writerows(zip_data)


Output

List_columns,list_Val
Name,        Tom
Age,         9
Weight,      8
City,        WA

5. write list to CSV writer newline


In this Python program example, the csv.writer(csvfile,delimiter=’,’) is used to create a CSV writer object and open() method to create and open CSV file in write mode.

The writerows() is used to write a row-wise list of lists to the CSV file.

Python Program

import csv
Animal_list= [ ['Tom', 9, 8, 'WA'],  ['Trex', 6, 15, 'CA'],  ['Kity', 7, 11, 'WA']]
with open('animal.csv', 'w', newline='') as csvfile:
         writer = csv.writer(csvfile,delimiter=',')
         writer.writerows(Animal_list)

Output

Tom,9,8,WA
Trex,6,15,CA
Kity,7,11,WA

6. Write list to CSV using Numpy


In this example, we have used the numpy module import numpy as np. The numpy module savetxt() method to list of list to CSV.

Each row value is separated by a delimiter comma (,) and fmt = %s is a single format string.

Python Program

import numpy as np 
List_rows = [['Tom', 9, 8, 'WA'],  ['Trex', 6, 15, 'CA'],  ['Kity', 7, 11, 'WA']] 
np.savetxt("animal.csv",List_rows, delimiter =",",  fmt ='% s') 

Output

Tom,9,8,WA
Trex,6,15,CA
Kity,7,11,WA

7. write list to CSV in Python Pandas


In this Python program, we will learn, for example how to write a list to CSV using Python Pandas. We will import module pandas Using “import pandas as pd

We have converted three lists ( list_name,list_age, list_city) to lists of dictionary and secondly dictionary to dataframe.

The pandas dataframe to_csv() to create a csv file from the dictionary.

Python Program

import pandas as pd  

list_age= [9,6,7]
list_city = ['WA', 'CA','WA']
list_name = ['Tom', 'Trex','Kity'] 
dict_of_list = {'name': list_name, 'age': list_age, 'city': list_city}
 #dictionary to df            
dfobj = pd.DataFrame(dict_of_list) 
dfobj.to_csv('animal.csv')

Output

,name,age,city
0,Tom,9,WA
1,Trex,6,CA
2,Kity,7,WA

Summary

In this post, we have learned 7 ways to write List to CSV in Python.