在Python中写入dbf时出错

8 投票
1 回答
2362 浏览
提问于 2025-04-17 21:15

我遇到了这个错误:

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

怎么解决这个问题呢?

这是我的 代码

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

1 个回答

10

dbf 和大多数数据库软件不一样,它不是把数据放在一个完全独立的结构里(比如一堆行作为元组),而是直接在 dbf 文件上操作。

我遇到的问题是,当我一次更新多个字段时:

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

如果在更新第一个字段之后发生了错误,我就会得到一个只部分更新的记录,这样记录内部就不一致了。

为了解决这个问题,我添加了一段代码,这段代码有点像是对每条记录进行的提交,激活它的方法是使用 withProcess

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

现在,如果发生错误,原来的值会被恢复;如果没有错误,新值就会被保存到磁盘上的 dbf 表中。

除了在记录上使用 with,你还可以在一堆记录上使用 Process,或者你可以避免这个问题,把数据收集在记录外面,然后一次性写入:

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

所以,回到你的代码,最简单的修复方法可能是:

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

撰写回答