Domanda

I got this err:

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

How to fix it?

This is my code:

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

Soluzione

dbf is different from most other DB packages in that instead of getting a completely seperate data structure (a bunch of rows as tuples, for example) you are working directly with the dbf file itself.

The problem I found myself running into was that when I would update multiple fields at once:

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

if an error happened any time after the first field I had a record that was only partially updated, and therefore no longer internally consistent.

To get around that problem I added code that it is kind of like commit on a per record basis, and the way to activate it is with with or with Process:

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

Now, if an error happens, the original values are restored; if no error happns, the new values are saved into the dbf table on disk.

Besides with on a record, you could also use Process on a bunch of records, or you could avoid the issue and collect your data outside the record and then write it all at once:

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

So, to get back to your code, the easiest way to fix it is probably:

with dbf.Table("aa.dbf") as table:
    for record in dbf.Process(table):
        record[3] = 200
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top