首页 > 解决方案 > 删除 dbf 文件/lib 中的空格

问题描述

我需要使用 python dbflib 过滤一个 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

问题是,要么dbflib 添加空格,要么我的 dbf 文件包含我看不到的空格。

因此,要查询一个名为 contains 的字段descengMattress我需要添加空格。

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

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

有没有办法删除空格,所以我可以简单地用'Mattress'而不是查询'Mattress '

谢谢!

标签: pythondbf

解决方案


您可以做几件事:

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

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

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

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


推荐阅读