Error when writing data into dbf in Python
Asked Answered
A

1

8

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
Allover answered 7/3, 2014 at 7:5 Comment(3)
Is the indentation as we see it correct?Amaliaamalie
@Tim: it is now.Phiphenomenon
@EthanFurman thanks, I had been wondering for the past 8 yearsAmaliaamalie
P
10

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
Phiphenomenon answered 7/3, 2014 at 15:33 Comment(2)
cool, it is very nice of u.Thanks, problem solved. dbf is a nice lib.Allover
With the last version of dbf module, the right syntax is: dbf.write(record, **new_data)Snowman

© 2022 - 2024 — McMap. All rights reserved.