Tutorial Python reading CSV file

Posted in Uncategorized

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Suppose we have a CSV (comma-separated value) file like this…

Note that there are no spaces after the comma delimiter otherwise you get space in the values read.

We can have Python read this CSV file using the “reader” from the “csv” module…

Each row will be an list like this…

Note that the for-loop needs to be inside the “with” block because it needs the file to be open at the time.

Read CSV with DictReader

Alternatively, you can use the DictReader (also from the csv module)…

However, with the DictReader, it expects the first row of the csv file to be a header row like this…

(Sorry, the header “Abreviation” should be spelled correctly as “Abbreviation”.)

When you read this in, then each “row” is an “OrderedDict” that looks like this…

In other words, each “row” is a dictionary, which means that you can call “items()” to get the key, value. But the tuple that is returned from items() is always in the order that it was placed. Unlike a regular dictionary, the order of items() is undetermined.

So if we change the code to be …

You get ..

where the keys “Month”, “Abreviation”, and “Num Days” are always in this order.


Related Posts

Tags

Share This