Search code examples
pythondbf

How to add a field to a dbf file?


I have something about like this:

from dbfpy import dbf
import random

db = dbf.Dbf('DMWWGS84/DMAWGS84.dbf',new=False)
db.addField(("Data","D"))
for record in db:
    print record
    record["Data"]=random.random()
db.close()

But it complains:

Traceback (most recent call last):
  File "merge_csv.py", line 5, in <module>
    db.addField(("Data","D"))
  File "/Users/alex/anaconda2/lib/python2.7/site-packages/dbfpy/dbf.py", line 246, in addField
    raise TypeError("At least one record was added, "
TypeError: At least one record was added, structure can't be changed

What record is it talking about? Is this a good way to do this?


Solution

  • Use my dbf library instead:

    pip install dbf

    (you may need to pip install enum34 first)

    and then the commands:

    # lightly tested
    
    import dbf
    import random
    
    db = dbf.Table('whatever.dbf')
    with db:
        db.add_fields('data N(12,7)')
        for record in db:
            dbf.write(record, data=random.random())
    

    NB: Writing random numbers to a date field will not work well.