我得到了这个错误:
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
最佳答案
dbf
与大多数其他 DB 包的不同之处在于,您直接使用 dbf 文件本身,而不是获得完全独立的数据结构(例如,一堆行作为元组)。
我发现自己遇到的问题是,当我一次更新多个字段时:
record.name = 'Some Name'
record.age = current_year -birth_year
record.hair_color = base_color * sun_tint
如果在第一个字段之后的任何时候发生错误,我的记录只会部分更新,因此内部不再一致。
为了解决这个问题,我添加了代码,它有点像在每条记录的基础上提交,激活它的方法是使用 with
或 流程
:
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
关于python - 在 Python 中将数据写入 dbf 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22243714/