Reading .CSV files using Python programming language

Last thursday our programing teacher gave us homework to read from a .csv file and do something with the information. Our task was to read from a file where our name, Email and the number of the programs we have written was entered and get the summary of the programs that the whole class has written. It isn’t a hard task at first look, but when I started doing it I got across a lot of problems. Now I’m gonna explain to you how to read from a .CSV file using Python. First you need some basic Python knowledge. I can’t help you with that so you need to google “Python tutorial” and get into the language a bit.

First download Python:

http://www.python.org/download/releases/3.3.0/

Then you need to download CSV:

http://www.object-craft.com.au/projects/csv/download.html (download the latest one and extract the folder to your python directory)

When you have done this things you can start typing the code in. First you need to import CSV into the program by typing:

import csv

Afterthat open the file by using “file = open(“filename.csv”, ‘r’)” (It’s important to use ‘r’ instead of ‘rb’, because you’ll get that error: “_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?) “)

The rest of the program is simple python code. However there are some thing that you need to know:

If you are using newer than python 2.6 you need to use “next(reader)” instead of “reader.next” which took me a lot time to understand. This right here is a simple tutorial on how to read .csv file with python:

http://www.coderholic.com/parsing-csv-data-in-python/

And here is my program:

https://github.com/powerworr/Python/blob/master/read_csv.py

If you have any other questions feel free to ask! 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s