Search code examples
pythondbf

Remove spaces in dbf file/lib


I need to filter a dbf file using the python dbf lib. I made a class with some methods over the dbf lib, so I have a method search that filter records.

def search(self, field_name: str, value: object) -> List:
    self._open_for_read()
    index = self._table.create_index(lambda rec: getattr(rec, field_name))
    records = index.search(match=(value,))
    return records

The problem is, either the dbf lib add blank spaces, or my dbf file contains blank space that I cant see.

So, to query a field named desceng that contain Mattress, I need to add blank spaces.

 records = hifis.search('desceng',  'Mattress                                                                        ')

The number of blank spaces seems to depend on field.

Is there a way to remove the blank spaces, so I can simply query with 'Mattress' instead of 'Mattress '?

Thanks!


Solution

  • There are a couple things you can do:

    • trim the trailing whitespace when you create the index:

      index = self._table.create_index(lambda rec: (getattr(rec, field_name) or '').strip())

    • use the Char class when opening the database as it automatically trims trailing whitespace:

      self._table = dbf.Table(..., default_data_types={'C':dbf.Char}