删除dbf文件/ lib中的空格

时间:2019-11-04 21:06:57

标签: python dbf

我需要使用python dbf lib过滤dbf文件。我通过dbf lib创建了带有某些方法的类,因此我有一个方法search可以过滤记录。

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

问题是dbf lib添加空格,或者我的dbf文件包含我看不到的空格。

因此,要查询包含desceng的名为Mattress的字段,我需要添加空格。

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

空格的数量似乎取决于字段。

有没有一种方法可以删除空格,因此我可以简单地使用'Mattress'而不是'Mattress '进行查询?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以做几件事:

  • 在创建索引时修剪尾随空白:

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

  • 在打开数据库时使用Char类,因为它会自动修剪尾随空白:

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