Search code examples
pythondbf

Python DBF | Moving new field to the first column


I am trying to copy the format of a old dbf file and add a additional column and make it the first column instead of the last. I am currently using Ethan Furman's dbf library.

Here is what I have tried but it only add a column at the end. I need it to add a column at the start.

    table = dbf.Table(filename=listOfDbf[6])
    table.open(dbf.READ_WRITE)
    custom = table.new(filename= user + "\\" + filename +'.dbf',default_data_types=dict(C=dbf.Char, D=dbf.Date, L=dbf.Logical))
    with custom:
        for record in table:
            custom.append(record)
    table.close()
    custom.open(dbf.READ_WRITE)
    custom.add_fields('PROJECT C(40)')
    table.close()

Expectation:

old dbf

Field 1 Field 2 Field 3 Field 4
Cell 1 Cell 2 Cell 1 Cell 2
Cell 3 Cell 4 Cell 1 Cell 2

new dbf (add new column)

PROJECT Field 1 Field 2 Field 3 Field 4
Cell x Cell 1 Cell 2 Cell 1 Cell 2
Cell x Cell 3 Cell 4 Cell 1 Cell 2

Solution

  • To get added fields at any location besides the end, you'll need to manually insert the field specification where you want it:

    import datetime
    import dbf
    
    # create test table
    tbl1 = dbf.Table(
            'tbl1.dbf',
            field_specs='field1 C(9); field2 N(3,0); field3 D; field4 M',
            default_data_types='enhanced',
            )
    tbl1.open(dbf.READ_WRITE)
    tbl1.append(('Me', 77, datetime.date(2023, 01, 17), 'imortant stuff'))
    tbl1.append(('You', 55, datetime.date(2015, 7, 1), 'more important stuff'))
    tbl1.open(dbf.READ_ONLY)
    
    # modify structure
    layout = tbl1.structure()
    layout.insert(0, 'project C(30)')
    
    # create new table
    tbl2 = tbl1.new('tbl2.dbf', field_specs=layout)
    tbl2.open(dbf.READ_WRITE)
    
    # copy records to new table
    for rec in tbl1:
        tbl2.append(rec)
    

    If you already know what the project field value should be, you can add it during the initial copy:

    for rec in tbl1:
        new_data = ('a project', ) + tuple(rec)
        tbl2.append(new_data)