Read and Write CSV Files in Python

CSV stands for Comma Separated Values. It is a standard text file in which values are separated by commas.

Python provides csv built-in module that implements classes to read and write tabular data in CSV format.

Reading a CSV File

To read a CSV file in Python, you must first import the csv module of Python, open the file using the open() function, and read the file using the csv module's reader() method. For example:

import csv

file_not_found = False
file = "test.csv"
    with open(file, 'r') as csvfile:
        csvreader = csv.reader(csvfile)

        #Read first row field names
        fields = next(csvreader)
        rows = []
        #Read csv data row by row
        for row in csvreader:

        print("Total number of data: %d" % (csvreader.line_num))
except FileNotFoundError as ex:
    print("Error File not found:" + str(ex))
    file_not_found = True
    if not file_not_found:
        print("Closing file...")

Writing to a CSV file

The csv module's writer() method returns a writer object. This writer object has methods such as writerow() and writerows() to write the user's data into the csv file. For example:

import csv

file = "test2.csv"

with open(file, mode='w') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    csvwriter.writerow(['Jonny', 'Programming', 'A'])
    csvwriter.writerow(['Joe', 'Engineering', 'B'])
    csvwriter.writerow(['Danny', 'Scientist', 'C'])
    csvwriter.writerow(['Leni', 'Doctor', 'D'])