In this post, we will learn How to Write a list of lists to CSV in Python or how to write a list of tuples to CSV in Python with a program example. We will use the Python CSV module.
1. Write list of lists to CSV in Python
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
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 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)
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
3. Write List of lists to CSV in Python Pandas
Using the panda’s module, first, we are converting list of lists to dataframe, then to_csv() method to write list of lists to csv, parameter header=List_columns passing list of columns.
- List_rows : It contain a list of tuples to be written to CSV file rows
- List_columns: to write first row that is columns or header.
Python Program
import pandas as pd
List_rows =[ ['Tom', 9, 8, 'WA'], ['Trex', 6, 15, 'CA'], ['Kity', 7, 11, 'WA']]
List_columns = ['Name', 'Age', 'Weight', 'City']
df = pd.DataFrame(List_rows)
df.to_csv('animal.csv', index=False, header=List_columns)
Output
Name Age Weight City
Tom 9 8 WA
Trex 6 15 CA
Kity 7 11 WA
4. Write list of lists to CSV in Python Numpy
In this program example, we will learn how to use the Numpy Module to save list of lists to CSV by using numpy.savetxt() method with the below parameter.
- The header : parameter to pass header=”Name, Age, Weight, City” columns name.
- deleimiter is used to separate the row value by comma(,).
- The fmt = %s is a single format string.
- comments=” : to elminate the # by default added to first column name.
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 =",",header="Name, Age, Weight, City", fmt ='% s',comments='')
Output
Name Age Weight City
Tom 9 8 WA
Trex 6 15 CA
Kity 7 11 WA
5. Write list of tuples to CSV in Python NumPy with specific format
In this program example, we will learn how to use Numpy Module to save list of lists to CSV by using numpy.savetxt() method with below parameters
- The header : parameter to pass list of columns name.
- deleimiter is used to separate the row value by comma(,).
- The fmt :We have specify datatype of each columns of numpy array and it combination of fmt=[‘%s’ , ‘%f’, ‘%d’,’%s’]
- comments=” : to elminate the # by default added to first column name.
Python Program
import numpy as np
list_Val= [ ('Tom', 9, 8, 'WA'), ('Trex', 6, 15, 'CA'), ('Kity', 7, 11, 'WA')]
dtype = [('Name', (np.str_, 10)), ('Marks', np.int32), ('weight', np.int32),('City', (np.str_, 5))]
np_array = np.array(list_Val, dtype=dtype)
np.savetxt('struct_array.csv', np_array , delimiter=',', fmt=['%s' , '%f', '%d','%s'], header='Name,,Age,weight,city', comments='')
Output
Name Age Weight City
Tom 9 8 WA
Trex 6 15 CA
Kity 7 11 WA
6. For loop to Write list of lists to CSV in Python
In this Python program example, the first row is written with the columnnames using writer.writerow(List_columns) method.
We are using for loop to iterate over each list of lists or 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:
writer = csv.writer(CSVFile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
writer.writerow(List_columns)
for row in List_rows:
writer.writerow(row)
Output
Name Age Weight City
Tom 9 8 WA
Trex 6 15 CA
Kity 7 11 WA
Summary
In this post we have learned how to write a list of lists to CSV in Python or how to write list of tuples to CSV in python with python program examples.