簡體   English   中英

在 Python 中將數據寫入 dbf 時出錯

[英]Error when writing data into dbf in Python

我得到了這個錯誤:

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或使用Process

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM