In this article let’s learn about how to save list to CSV in python. CSV (Comma Separated Values) files are used to store data in a tabular format. 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 article will cover several methods for saving lists to CSV in python.
Contents
Using csv Module
import csv
# column names
fields = ['Student', 'Department', 'Year', 'Grade']
# data rows of csv file
rows = [ ['SAM', 'CS', '2', '8.0'],
['Joel', 'CSE', '2', '9.6'],
['Richard', 'IT', '2', '8.3'],
['Loen', 'EC', '1', '7.5'],
['Paul', 'CGO', '3', '8'],
['Husain', 'IT', '2', '9']]
with open('output.csv', 'w') as f:
write = csv.writer(f)
write.writerow(fields)
write.writerows(rows)
Output:

List to csv using Pandas
# importing pandas as pd
import pandas as pd
# list of name, degree, score
nme = ["SAM", "Joel", "Richard", "Paul"]
deg = ["MBA", "BCA", "M.Tech", "MBA"]
scr = [95, 56, 70, 90]
# dictionary of lists
dict = {'Student': nme, 'Department': deg, 'Score': scr}
df = pd.DataFrame(dict)
# saving the dataframe
df.to_csv('output.csv')
Output:

Save List to csv using Numpy Module
import numpy as np
# data rows of csv file
rows = [ ['SAM', 'CS', '2', '8.0'],
['Joel', 'CSE', '2', '9.6'],
['Richard', 'IT', '2', '8.3'],
['Loen', 'EC', '1', '7.5'],
['Paul', 'CGO', '3', '8'],
['Husain', 'IT', '2', '9']]
# using the savetxt
# from the numpy module
np.savetxt("output.csv",
rows,
delimiter =", ",
fmt ='% s')
Output:

Also Read :
How to Get Python dictionary keys as a List
How To Convert Python Unicode Characters To String | Python