Reading & Writing CSV with Python

pradeep's Avatar author of Reading & Writing CSV with Python
This is an article on Reading & Writing CSV with Python in Python.
CSV files are quite common these days owing to the fact that CSV files are simple text and make data transfer between different systems very easy. CSV stands for Comma Separated Values, i.e. the fields are separated by comma, so there exists similar formats where the separator is a different character like tab, or semi-colon. We have seen working with CSV in Perl & PHP, so why not in Python.

Python 2.4 onwards CSV reading and writing was made easier by inclusion on an in-built module csv, the module has reader & writer objects for reading & writing CSV files respectively.

Now, let's get our hands dirty with some code.

Reading CSV Files



First let's look at a very basic example, which will read a CSV file and print out the fields:

Code: Python
import csv
csv_reader = csv.reader(open("g4eposts.csv", "rb"))
for fields in csv_reader:
    print fields

Now, let us look at a scenario where the delimiter is : instead of comma, a good example of such a file is /etc/passwd:

Code: Python
import csv
## get the reader object, and specify no quoting
csv_reader = csv.reader(open("/etc/passwd", "rb"), delimiter=':', quoting=csv.QUOTE_NONE)
for fields in csv_reader:
    print fields

Quoting is required when any field value contains the delimiter character, we'll look at it in the next section.

Writing CSV Files



A writing example:

Code: Python
import csv

## get writer object
csv_writer = csv.writer(open('names.csv', 'wb'), quoting=csv.QUOTE_MINIMAL)

## write a few rows
csv_writer.writerow(['Tanaz','UK'])
csv_writer.writerow(['Navin','IN'])
csv_writer.writerow(['Manindar, Shikha','US'])
csv_writer.writerow(['Anjali','IN'])

Here's the output:
Code:
Tanaz,UK
Navin,IN
"Manindar, Shikha",US
Anjali,IN

As you can see the field value that contained a [B],[B] was quoted automatically.

References



http://docs.python.org/library/csv.html