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

标签 python dbf

我得到了这个错误:

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/

相关文章:

python - 使用类中的 return 语句从类获取值

r - 导入不带行分隔符的固定宽度数据文件

java - 读/写 xBASE (DBASE 3-5/DBF) 文件

python - 从 dbf 文件中选择字段

php - 需要构建一个应用程序来远程上传一个dbf文件并更新mysql数据库

Python _ValueError : invalid literal for int() with base 10: _very weird

javascript - 使用 CryptoJS 加密,使用 PyCrypto 解密(将 CryptoJS 调整为 PyCrypto 默认值)

python - 使用每个元素 x 次将 python 数组映射到 x 倍长的数组

python - 将 .CSV 转换为 .DBF(dBASEIII) VFP 6.0,一切都变成备注字段

python - 为什么我会收到 [Errno 7] Argument list too long 和 OSError : [Errno 24] Too many open files when using mrjob v0. 4.4?