Showing posts with label standard module. Show all posts
Showing posts with label standard module. Show all posts

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.

Monday, April 19, 2010

Weekly Python module: atexit

New idea about few posts. What about smalltalk about one Python module in a week?

Lets go!



For this week Python standard module 'atexit'. Whole purpose of this module is to provide functions that will be executed at normal interpreter exit.

It has only one function register, that takes function and make sure that every function that was registered will be called in last in, first out order. If you know 'atexit()' C routine you will be familiar with it.

Small example:

def goodbye(name, adjective):
    print 'Goodbye, %s, it was %s to meet you.' % (name, adjective)

import atexit
atexit.register(goodbye, 'Donny', 'nice')

# or:
atexit.register(goodbye, adjective='nice', name='Donny')

register function can also be used as decorator:

import atexit

@atexit.register
def goodbye():
    print "You are now leaving the Python sector."