Create a CSV file from a list in Python

In this article, we will discuss different ways to create a csv file from lists in Python.

Table Of Contents

Create a CSV file from a single List in Python

Open csv file with the open() function in write mode, and get a file object. Pass this file object to the writer() function of csv module, to get a csv writer object. Then call its writerow() function with a list of strings to add it as a row in the csv file. Let’s see an example,

import csv

# A list containing the some strings
heading = ['Name', 'Age', 'City', 'Country']

# Open the csv file in write mode
with open('students.csv', 'w') as fileObj:
    # Create a csv writer object
    writerObj = csv.writer(fileObj)
    # Add a single row in CSV file
    writerObj.writerow(heading)

It created a csv file students.csv, with only one row. Contents of the file will be,

Name,Age,City,Country

Create a CSV file from a list of lists in Python

We can also create a csv file with multiple rows from list of lists. Each sublist in main list, will act as a row of the csv file. For that, open csv file with the open() function in write mode, and get a file object. Pass this file object to the writer() function of csv module, to get a csv writer object. Then call its writerows() function with a list of lists. It will add each sublist as a row in the csv file. Let’s see an example,

Advertisements
import csv

# A List of lists
students = [['Ritika', 27, 'Delhi', 'India'],
            ['Mark', 28, 'Sydney', 'Australia'],
            ['Suse', 29, 'Las Vegas', 'USA'],
            ['Shaun', 30, 'London', 'UK']]

# A list containing the heading of csv file
heading = ['Name', 'Age', 'City', 'Country']

# Open the csv file in write mode
with open('students.csv', 'w') as fileObj:
    # Create a csv writer object
    writerObj = csv.writer(fileObj)
    # Add a single row in CSV file
    writerObj.writerow(heading)
    # Add list of lists as multiple rows
    writerObj.writerows(students)

It created a csv file students.csv, with multiple rows. Contents of the file will be,

Name,Age,City,Country
Ritika,27,Delhi,India
Mark,28,Sydney,Australia
Suse,29,Las Vegas,USA
Shaun,30,London,UK

Create a CSV file by using lists as columns

Suppose we have four lists,

names   = ['Ritika', 'Mark', 'Suse', 'Shaun']
age     = [27, 28, 29, 30]
city    = ['Delhi', 'Sydney', 'Las Vegas', 'London']
country = ['India', 'Australia', 'USA', 'UK']

We can use each list as a column and create a csv file from these four lists. Contents of the csv file will be like,

Name,Age,City,Country
Ritika,27,Delhi,India
Mark,28,Sydney,Australia
Suse,29,Las Vegas,USA
Shaun,30,London,UK

To do that, we will create a dictionary of key-value pairs. In each pair, key is the column name and value field contains a list i.e. column values. Then use this dictionary to create a Pandas DataFrame object. After that, set the column with label “Name” as the index column of DataFrame. Then call the to_csv() function of DataFrame to store the data in csv file. Let’s see an example,

import pandas as pd

# Create multiple lists
names   = ['Ritika', 'Mark', 'Suse', 'Shaun']
age     = [27, 28, 29, 30]
city    = ['Delhi', 'Sydney', 'Las Vegas', 'London']
country = ['India', 'Australia', 'USA', 'UK']

# Create a dictionary where each item contains
# a column for csv file
mapping = { 'Name' : names,
            'Age' : age,
            'City' : city,
            'Country' : country}

# Create a DataFrame from mapping
df = pd.DataFrame(mapping)

# Set the column 'Name' as index
df = df.set_index('Name')

# Create csv file from DataFrame
df.to_csv('students.csv') 

It created a csv file students.csv, with multiple rows. Contents of the file will be,

Name,Age,City,Country
Ritika,27,Delhi,India
Mark,28,Sydney,Australia
Suse,29,Las Vegas,USA
Shaun,30,London,UK

Create a CSV file from a list of lists using NumPy

We can pass list of lists to the savetxt() function of numpy module, along with the filename and delimeter character. It will save each sublist as a row in the csv file. let’s see an example,

import numpy as np

# A List of lists
students = [['Ritika', 27, 'Delhi', 'India'],
            ['Mark', 28, 'Sydney', 'Australia'],
            ['Suse', 29, 'Las Vegas', 'USA'],
            ['Shaun', 30, 'London', 'UK']]

# using the savetxt () function
# from the numpy module
np.savetxt("students.csv", students, delimiter =",", fmt ='%s')

It created a csv file students.csv, with multiple rows. Contents of the file will be,

Ritika,27,Delhi,India
Mark,28,Sydney,Australia
Suse,29,Las Vegas,USA
Shaun,30,London,UK

Summary

We learned about different ways to create a csv file from lists in Python. Thanks.

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top