删除dbf文件/lib中的空格

2024-06-16 09:55:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要使用pythondbf库过滤dbf文件。我在dbf库上用一些方法创建了一个类,因此我有一个方法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文件包含我看不到的空格

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

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

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

是否有一种方法来移除空白空间,所以我可以简单地用^ {< CD6>}来代替^ {< CD7>}?

谢谢


Tags: 文件方法nameselffieldsearchindexvalue
1条回答
网友
1楼 · 发布于 2024-06-16 09:55:56

你可以做以下几件事:

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

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

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

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

相关问题 更多 >