Package Gnumed :: Package pycommon :: Module gmdbf
[frames] | no frames]

Module gmdbf

source code


This is a module for reading dbf files.

It has been modified thanks to suggestions and patches from Jeff Bauer
and Kevin Dahlhausen. Unfortunately I lost patches which fix
endianness problems, which were sent to me by someone, so that will
have to wait. I do not use this module much these days, but since it
seems to be in use "out there" I thought I would finally make an
update available. This version should be more portable. Also, rather
than printing an error message an exception is now raised when the dbf
file appears to be corrupt.

Usage: the following

import dbf
db = dbf.dbf('mydata.dbf')

creates a dbf object db associated with an existing dbf file
'mydata.dbf'.  The dbf file is opened by the constructor. If the file
is not there IOError is raised. If the file appears not to be a dbf
format file, TypeError is raised.

If you prefer to create a dbf object, but open the actual file later,
you can use the following:

import dbf
db = dbf.dbf('mydata.dbf', openit=0)

and then you can call

db.open()

to actually open the file. Note that the constructor, if called this
way, does not verify that the file is there, so the IOError exception
is raised by the call to open.

Once the dbf object is created and opened (implicitly or not), the
following are available:

-- db.fields  : returns a a list of tuples describing the fields
-- db.nrecs   : returns the number of records
-- db[n]      : returns a tuple containing record number n (0 <= n < nrecs)
-- db.status(): prints some essential data about the dbf file

So to list the first two fields of mydata.dbf, assuming they are string
fields, one might write:

import dbf
from string import strip
db=dbf.dbf('mydata.dbf')
for k in db:
    print "%s, %s" % (strip(k[1]), strip(k[2]))


Good luck!

Classes
  dbf
Variables
  __package__ = 'Gnumed.pycommon'

Imports: unpack