How to write CSV files in Python

In this tutorial, we will learn about how to write CSV files in Python.
CSV files are easier to create and handle. Therefore they are widely used for sharing a large amount of data or information within organizations. Another application field of CSV files is Data Science.

So, let’s start.

What are CSV files?

A Comma separated file (CSV) file is a text file that contains information separated by commas. CSV files store tabular data in text format. CSV files are saved with .csv extension. Microsoft Excel or Google spreadsheets work with CSV files commonly.

Comma separated CSV file

NOTE: Instead of a comma you can also use other delimiters like semicolon to separate the information.

Writing CSV files

In Python, we need to import the CSV module to work with CSV files.

import csv

CSV module provides us with

  • csv.writer
  • csv.DictWriter class, to write a csv files


The csv.writer class return a writer object which converts the user’s data into a comma-separated string or any other delimited string.

With the help of the following functions of csv.writer class, we can write the string produced by csv.writer class into CSV files.

  • writerow(): This is mostly used to write the title row because it writes 1 row at a time
  • writerows(): writerows function writes multiple rows of data at a time.

SYNTAX: csv.writer(csvfile, dialect=’excel’, **fmtparams)

csv.writer Python


import csv
with open('example.csv', 'w',newline="") as file:
writer = csv.writer(file)
# Adding Header/Title row using writerow 
writer.writerow(["S.No", "Country", "Population"])
# Adding Multile entries at once using writerows
writer.writerows([[1, "India", "140 Crores"],[2, "China", "150 Crore"],[3,"USA","40 Crore"]])


CSV excel screenshot


The csv.DictWriter class returns a writer object that is used to write CSV files from Python dictionaries.

SYNTAX: csv.DictWriter(csvfile, fieldnames, restval=”, extrasaction=’raise’, dialect=’excel’, *args,

csv python result


import csv
with open('example.csv', 'w', newline='') as file:
# Header/Title row 
    fieldnames = ['S.No','Country', 'Population']
    writer = csv.DictWriter(file, fieldnames=fieldnames)
# writeheader() function is used to write the header
#writerows function is used to write the dictionary values into CSV file
    writer.writerow({'S.No':'4','Country': 'Indonesia', 'Population': '32 crore'})
    writer.writerow({'S.No':'5', 'Country':'Brazil', 'Population': '25 crore'})
    writer.writerow({'S.No':'6', 'Country':'Nigeria', 'Population': '22 crore'})



Hope you liked this tutorial.

Also, check the following links.

Leave a Reply

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