How to add a field to a dbf file?

自闭症网瘾萝莉.ら 提交于 2020-01-03 03:13:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!