Error when writing data into dbf in Python

冷暖自知 提交于 2019-12-01 01:43:14

问题


I got this err:

DbfError: unable to modify fields individually except in with or Process()

How to fix it?

This is my code:

with dbf.Table("aa.dbf") as table:
  for record in table:
    record[3] = 200

回答1:


dbf is different from most other DB packages in that instead of getting a completely seperate data structure (a bunch of rows as tuples, for example) you are working directly with the dbf file itself.

The problem I found myself running into was that when I would update multiple fields at once:

record.name = 'Some Name'
record.age = current_year -birth_year
record.hair_color = base_color * sun_tint

if an error happened any time after the first field I had a record that was only partially updated, and therefore no longer internally consistent.

To get around that problem I added code that it is kind of like commit on a per record basis, and the way to activate it is with with or with Process:

with record:  # capture current values
    record.field1 = something
    record.field2 = something_else
    record.field3 = another_thing
# now some other code

Now, if an error happens, the original values are restored; if no error happns, the new values are saved into the dbf table on disk.

Besides with on a record, you could also use Process on a bunch of records, or you could avoid the issue and collect your data outside the record and then write it all at once:

for record in table:
    new_data = {}
    new_data['field1'] = 'a name'
    new_data['field2'] = an_age
    dbf.write(record, new_data)

So, to get back to your code, the easiest way to fix it is probably:

with dbf.Table("aa.dbf") as table:
    for record in dbf.Process(table):
        record[3] = 200


来源:https://stackoverflow.com/questions/22243714/error-when-writing-data-into-dbf-in-python

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