Wednesday, May 12, 2010

Weekly Python module: csv

Csv is quite common way for saving data. And it is the most simple. Coma separated values, but coma do not have to be comas, maybe tabs, asteriks, quotation marks. Also quotation marks are usually used to mark  text - strings. And new line char also counts as 'coma'.

Python have great tool, that removes all complexity of csv. And is it named csv, You would not guess, right?

>>> import csv 
>>> spamReader = csv.reader(open('eggs.csv'), delimiter=' ', quotechar='|') 
>>> for row in spamReader: 
... print ', '.join(row) 
Spam, Spam, Spam, Spam, Spam, Baked Beans Spam, Lovely Spam, Wonderful Spam

reading csv is simple, but be aware that spamReader is one use only, so if you have to go through data multiple times, just copy them in first pass, or create reader before each pass.

Writing is the same. Change 'reader' to 'writer', and you are ready to write down your data. using writerow() or writerows() .

For more info look at python docs. There is one more feature to discover. Dialects (csv can detect delimiter and quotechar automagicly) are nice, but not required to use csv.

PyGame tutorials

This blog is not the only project about python tutorials, I made.

Here is nice site with PyGame tutorials, I've made year ago.