12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

14.6. Databases 139<strong>Python</strong> starts by executing thetry clause. If all goes well, it skips theexceptclause and proceeds.Ifan exception occurs, itjumps out of thetryclause and executes theexceptclause.Handling an exception with a try statement is called catching an exception. In this example, theexcept clause prints an error message that is not very helpful. In general, catching an exceptiongives you a chance tofix theproblem, or tryagain, or at least end theprogram gracefully.14.6 DatabasesAdatabaseisafilethatisorganizedforstoringdata. Mostdatabasesareorganizedlikeadictionaryinthesensethattheymapfromkeystovalues. Thebiggestdifferenceisthatthedatabaseisondisk(orother permanent storage), soitpersistsafterthe program ends.The module anydbm provides an interface for creating and updating database files. As an example,I’llcreate a database that contains captions for image files.Opening adatabase issimilartoopening other files:>>> import anydbm>>> db = anydbm.open('captions.db', 'c')The mode'c' means that the database should be created if it doesn’t already exist. The result is adatabase object that can be used (for most operations) like a dictionary. If you create a new item,anydbmupdates the database file.>>> db['cleese.png'] = 'Photo of John Cleese.'When you access one of the items,anydbmreads the file:>>> print db['cleese.png']Photo of John Cleese.Ifyou make another assignment toan existingkey,anydbmreplaces theold value:>>> db['cleese.png'] = 'Photo of John Cleese doing a silly walk.'>>> print db['cleese.png']Photo of John Cleese doing a silly walk.Many dictionary methods, like keys and items, also work with database objects. So does iterationwithaforstatement.for key in db:print keyAs withother files, you should closethe database when you are done:>>> db.close()14.7 PicklingAlimitationofanydbmisthatthekeysandvalueshavetobestrings. Ifyoutrytouseanyothertype,you get anerror.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!