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 has a built-in module functions to open and read CSV files.

The open() function opens a file and return it as a file object.

Read CSV Files

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.


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...")

Write To CSV Files

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.


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'])