How to read and write csv file using Python

This tutorial is written for Python 3, but it also works for Python 2

To read and write CSV using Python, we use csv module

Read CSV file #

A short usage example #

import csv
with open('sample.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    for r in reader:
        print(r)

Reading a file with an alternate format: #

import csv
with open('sample', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=':', quoting=csv.QUOTE_NONE)
    for row in reader:
        print(row)

Asume sample.csv file has content:

Name, Address
Bob, 87 Abc Street

Catching and reporting errors while reading CSV file #

import csv, sys
filename = 'sample.csv'
with open(filename, newline='') as csvfile:
    reader = csv.reader(csvfile)
    try:
        for r in reader:
            print(r)
    except csv.Error as ex:
        sys.exit('File {} at line {}: {}'.format(filename, reader.line_num, ex))

Write CSV file #

A short usage example #

import csv
with open('sample.csv', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["header ", "Header 2", "Header 3", "Header 4"])
    writer.writerow([1, 2, 3, 4])

Since open() is used to open a CSV file for reading, the file will by default be decoded into unicode using the system default encoding. To decode a file using a different encoding, use the encoding argument of open:

import csv
with open('some.csv', newline='', encoding='utf-8') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(row)

If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms such as Windows that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.

Tags:

Python