在Python中将数据写入dbf时出错

UnZ*_*ike 7 python dbf

我犯了这个错误:

DbfError: unable to modify fields individually except in with or Process()
Run Code Online (Sandbox Code Playgroud)

怎么解决?

这是我的代码:

with dbf.Table("aa.dbf") as table:
  for record in table:
    record[3] = 200
Run Code Online (Sandbox Code Playgroud)

Eth*_*man 9

dbf 与大多数其他数据库包不同,它不是获得完全独立的数据结构(例如,一串行作为元组),而是直接使用dbf文件本身.

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

record.name = 'Some Name'
record.age = current_year -birth_year
record.hair_color = base_color * sun_tint
Run Code Online (Sandbox Code Playgroud)

如果在第一个字段之后的任何时间发生错误,我的记录只是部分更新,因此不再内部一致.

要解决这个问题,我添加的代码,它是一种喜欢犯在每记录的基础,并激活它与方式withProcess:

with record:  # capture current values
    record.field1 = something
    record.field2 = something_else
    record.field3 = another_thing
# now some other code
Run Code Online (Sandbox Code Playgroud)

现在,如果发生错误,则恢复原始值; 如果没有错误,则新值将保存到dbf磁盘上的表中.

除了with记录之外,您还可以使用Process一堆记录,或者您可以避免问题并在记录之外收集数据,然后立即写入:

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

因此,要回到您的代码,修复它的最简单方法可能是:

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