[Tutor] Create simple dbf files

Remco Gerlich scarblac@pino.selwerd.nl
Mon, 14 May 2001 12:43:03 +0200


On  0, "Mr. Razak" <arazak@kansai.com.my> wrote:
> 1. How to create simple dbf files.
>     Field    "part name", "part number","quantity order"
>     Type    "String","String","Numeric"

Simple? Use shelves. Types aren't very relevant in Python, of course.

import shelve

d = shelve.open(filename)

# Store items by part number
d[2343] = ("Piece of string", 35543)
d[2344] = ("Can of spam", 10)

d.close() # That's all, it's stored

# Now read them in
d = shelve.open(filename)
for partnumber in d.keys():
   print ("Partnumber: %d Part name: %s Quantity: %d" %
          (partnumber, d[partnumber][0], d[partnumber][1]))
d.close()

Storing them like tuples like this is pretty simple, a dictionary works
as well, or a class instance. You need some key (like the part number) to
use as an index, but you need that anyway.

Shelve is a layer over anydbm, which works the same way, but can only store
strings as values. Shelve converts your data to strings and then puts those
in the dbm. In effect the shelve works just like a persistent dictionary in
which you put data. Simplicity.

> 2. How to differenciate between txt files and dbf files in python.

You could use whichdb.whichdb(filename), which returns the empty string ('')
if the file's format can't be guessed, in which case it's not a dbm Python
recognizes. Returns None when the file can't be opened.

Now go read the library reference for shelve, anydbm and whichdb before you
use them :-)

-- 
Remco Gerlich