1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Reading & Writing CSV with Python

Discussion in 'Python' started by pradeep, Jun 21, 2012.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    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 [THREAD=11157]Perl[/THREAD] & [THREAD=28520]PHP[/THREAD], 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:
    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:
    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:
    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 , was quoted automatically.

    References



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

Share This Page