How to change dbf files in Python

Suppose I have a different number of dbf files in some folders in the root directory, d:\myfolder . The contents of the dbf file are as follows:

 Field1 11110481123 12150480021 ... 

I want to add a field (e.g. Field1 ) that contains only the last 4 digits of the values ​​in Field2 .

 Field1 Field2 11110481123 1123 12150480021 0021 ... ... 

Then I want to remove Field1 .

How can I do the job for all dbf files that are scattered across different folders in Python?

+4
source share
2 answers

You will need a module called dbf , accessible via pypi ( pip install dbf ). Here is a snippet of how you can add and remove fields from a table:

 import dbf table = dbf.Table('t1', 'field1 N(12, 0)') for record in ((11110481123,), (12150480021,)): table.append(record) table.close() # extend the existing table dbf.add_fields('t1', 'field2 N(4, 0)') table = dbf.Table('t1') records = table.sql('select *') for record in records: record.field2 = int(str(record.field1)[-4:]) table.close() dbf.delete_fields('t1', 'field1') 

Although it would be much less to calculate the intensity, just go to the first field and change it to save the last 4 digits of its value.

+4
source

Using the above dbf library (plus my other library, antipathy ), these are (roughly) the steps you will take:

 # untested import dbf from antipathy import Path for path, dirs, files in Path.walk('.'): files = [f for f in files if f.ext == '.dbf'] for db in files: if I_want_to_change_this_table(db): with dbf.Table(db) as db: db.add_fields('Field2 C(4)') for record in db: dbf.write(Field2=record.Field1[-4:]) db.delete_fields('Field1') db.pack() 

I_want_to_change_this_table() is a function that you provide if you do not want to modify each table, only some of them. If you want to change them, you can delete this line.

+1
source

Source: https://habr.com/ru/post/1410861/


All Articles