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.

How to Read 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.

Example

import csv

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

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

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

How to Write 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.

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

print("Complete...")