Skip to content
Home » How To Convert Python List To CSV File | Python

How To Convert Python List To CSV File | Python

In this tutorial let’s learn about How To Convert Python List To CSV File | Python.

A CSV (Comma Separated Values) file is a simple file format for storing tabular data. The CSV file format is used to store tabular data (numbers and text) in plain text. Each line in the file represents a data record. Each record is made up of one or more fields that are separated by commas. The name of this file format comes from the use of the comma as a field separator.

This post will go over several methods for saving Python lists to CSV file.

Convert Python List To CSV File using csv Module

In the below example, we first imported the csv module. Then we created two lists.

  • rows
  • columns


The columns of the csv file are defined by the columns list, and rows are a list of lists that will construct rows of the csv file. Use the with command to open a student.csv file; if one does not exist, it will create one for us and write the rows and columns to it.

Code Example :

import csv

# column names
columns = ['Student', 'Subject', 'Marks']
	
# rows
rows = [ ['Ankit', 'maths', '86'],
		['John', 'social', '96'],
		['Jenny', 'computer', '57'],
		['Rosie', 'maths', '93'] ]

with open('student.csv', 'w') as f:
	write = csv.writer(f)
	write.writerow(columns)
	write.writerows(rows)

Output :

Convert Python List To CSV File using csv Module

The file is initially opened in the code using Python’s standard open() command. You can now write data to the file object f.

Then you send this file object to the CSV writer’s function Object(), which implements some additional methods and effectively wraps the file object, giving you with new CSV-specific capabilities like the writerows() method. You now send a list of lists to the CSV writer’s writerows() method, which converts the list of lists to CSV format.

Convert List To CSV File using Pandas to_csv() in Python

You can convert a list of lists to a Pandas DataFrame, which has powerful capabilities like the to csv() method. The DataFrame is an extremely powerful data structure that allows you to conduct a variety of operations. One of these is the to csv() method, which allows you to save the contents of the array to a CSV file.

Code :

import pandas as pd

# rows
students = [ ['Student', 'Subject', 'Marks'],
    ['Ankit', 'maths', '86'],
		['John', 'social', '96'],
		['Jenny', 'computer', '57'],
		['Rosie', 'maths', '93'] ]

df = pd.DataFrame(students)
df.to_csv('student.csv', index=False, header=False)

Ouput:

Convert List To CSV File using Pandas to_csv() in Python

To convert a list to a csv file, first convert the list to a dataframe, then use the to_csv() method to convert the dataframe to a csv file.

Code Example :

# importing pandas as pd
import pandas as pd

	
# columns
names = ["Ankit", "John", "Jenny", "Rosie"]
sub = ["maths", "social", "computer", "maths"]
marks = [86, 96, 57, 93]
	
# dictionary of columns list
dict = {'Student': names, 'Subject': sub, 'Marks': marks}
	
df = pd.DataFrame(dict)
	
# dataframe
df.to_csv('student.csv')

Output :

Convert List To CSV File using Pandas to_csv() in Python

In the above code we have declared the columns and then created a dictionary. The used pd.DataFrame to create a dataframe from the dictionary and used to_csv() method to to create a CSV file.

Convert Python List To CSV File using Numpy savetext() Method

NumPy is the backbone of Python’s data science and machine learning capabilities. Pandas too makes advantage of NumPy arrays to implement critical functionality.

You may convert a list of lists to a CSV file by using NumPy’s savetext() method and giving the NumPy array that results from the conversion as an argument.

Code Example :

import numpy as np

# rows
students = [ ['Student', 'Subject', 'Marks'],
    ['Ankit', 'maths', '98'],
		['John', 'social', '93'],
		['Jenny', 'computer', '77'],
		['Rosie', 'maths', '95'] ]


array = np.array(students)
np.savetxt('student.csv', array, delimiter=',', fmt="% s")

Output :

Convert Python List To CSV File using Numpy savetext() Method

Conclusion

In this tutorial we learnt different ways to convert Python lists to CSV files using various approaches. The suitable approach can be picked as per the requirement and the format of data we have. Hope all the approaches are clear.

Similar Posts:

Python Program to Sort list of tuple by Nth element of tuple
How To Convert Python Set into Tuple | Python
How to Convert String to Float in Python