Python DBF:如何将 .cdx 索引与 .dbf 关联 table

Python DBF: How to associate a .cdx index with a .dbf table

我被赋予了一项模糊的任务,即从各种 Visual FoxPro tables 中自动提取数据。

有几对 .DBF.CDX 文件。使用 Python dbf 包,我似乎可以使用它们。我有两个文件,一个 ABC.DBF 和一个 ABC.CDX。我可以使用

加载 table 文件
>>> import dbf
>>> table = dbf.Table('ABC.DBF')
>>> print(table[3])
  0 - table_key : '\x00\x00\x04'
  1 - field_1   : -1
  2 - field_2   : 0
  3 - field_3   : 34
  4 - field_ 4  : 2
  ...

>>>

据我了解,.cdx 文件是索引。我怀疑对应于 table_key 字段。 According to the author, dbf 可以读取索引:

I can read IDX files, but not update them. My day job changed and dbf files are not a large part of the new one. – Ethan Furman May 26 '16 at 21:05

读书就是我需要做的。我看到存在四个 class,IdxIndexIndexFileIndexLocation。这些似乎是不错的候选人。

Idx class 读入 table 和文件名,这很有希望。

>>> index = dbf.Idx(table, 'ABC.CDX')

不过我不确定如何使用这个对象。我看到它有一些生成器 backwardforward,但是当我尝试使用它们时出现错误

>>> print(list(index.forward()))
dbf.NotFoundError: 'Record 67305477 is not in table ABC.DBF'

如何将 .cdx 索引文件关联到 .dbf table?

.idx.cdx不一样,dbf目前无法读取.cdx个文件。

如果需要对table进行排序,可以创建内存索引:

my_index = table.create_index(key=lambda r: r.table_key)

您还可以创建一个完整的函数:

def active(rec):
    # do not show deleted records
    if is_deleted(rec):
        return DoNotIndex
    return rec.table_key

my_index = table.create_index(active)

然后遍历索引而不是 table:

for record in my_index:
    ...