问题
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?
回答1:
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.
回答2:
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())
来源:https://stackoverflow.com/questions/37891686/how-to-add-a-field-to-a-dbf-file