Opening and searching dBase III (DBF) databases in Python

Stanley Switalski picture Stanley Switalski · Dec 23, 2012 · Viewed 10.6k times · Source

I'm looking to develop an application in python which needs to search through a dBase III database file (DBF). I've been searching for a while now, but I cannot find any good documentation on how to do this. I've tried using DBFpy but cannot find any documentation on how to index/search a column. I've also tried to follow the advice in this thread but apparently my DBF file is "closed." I looked at the calls listed here but could not determine how to "open" the file. Could anyone recommend a python module for working with DBF files with documentation or instruct me how to properly use other DBF python modules. Thanks!

Answer

Ethan Furman picture Ethan Furman · Dec 23, 2012

Using my dbf module the basic flow is something like:

import dbf

some_table = dbf.Table('/path/to/table.dbf')  # table is closed
some_table.open()
index = some_table.create_index(record_indexer)
.
.
.
records = index.search(match=(some_value,))   # returns a dbf.List of matching records

and record_indexer is a function that returns the appropriate index value; it can be as simple as

lambda rec: rec.desired_field

or as complex as you need:

def record_indexer(record):
    if record.that_field == 'bad value':
        return dbf.DoNotIndex             # record is ignored
    return record.this_field, record.other