Adding Entries to a DBM File


import anydbm cityDB = anydbm.open("city.dbm", 'n') for flight in flights:     cityDB[flight] = cities[i] cityDB.close()

The anydbm module provides a generic interface, allowing you to open databases based on several different lower-level packages that can be installed on the system. When imported, the anydbm module searches for the dbm, gdbm, and bsddb packages that provide access to the UNIX dbm, GNU DBM, and Berkely DB libraries, respectively. If none of those packages are available, then the dumbdbm module is loaded to provide access to a simple DBM-style database library.

The adybdm module provides the open(filename [,flag [, mode]]) function that allows you to open and create databases (see the "Opening and Closing Files" phrase of Chapter 4, "Managing Files," for more details).

Note

When creating a new database, anydbm will try to use the database module that was first installed on the system.


The open function returns a database object that behaves much the same as a dictionary. Entries can be added to the database by assigning a value to a key using the d[key] = value syntax. The key must be a standard string, and the value must also be a standard string, except in the shelve module discussed in later phrases.

import anydbm cities = ["Dallas", "Los Angeles", "New York"] flights = ["1144", "1045", "1520"] times = ["230pm", "320pm", "420pm"] #Create DBM file cityDB = anydbm.open("city.dbm", 'n') timeDB = anydbm.open("time.dbm", 'n') #Add entries i = 0 for flight in flights:     cityDB[flight] = cities[i]     i += 1 i = 0 for flight in flights:     timeDB[flight] = times[i]     i += 1 print cityDB.items() print timeDB.items() #Close DBM file cityDB.close() timeDB.close()


add_dbm.py

[('1144', 'Dallas'), ('1045', 'Los Angeles'),  ('1520', 'New York')] [('1144', '230pm'), ('1045', '320pm'),  ('1520', '420pm')]]


Output from add_dbm.py code



Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net