BigBoy1337
BigBoy1337

Reputation: 5023

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?

Upvotes: 1

Views: 2894

Answers (2)

Mauro Assis
Mauro Assis

Reputation: 435

There´s a bug in this answer, you should open the file before use it:

import dbf
import random

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

Upvotes: -1

Ethan Furman
Ethan Furman

Reputation: 69298

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.

Upvotes: 3

Related Questions