Skip to main content
 首页 » 编程设计

带有 .dbf 表的 Python DBF : How to associate a . cdx 索引

2024年09月07日8oomusou

我被赋予了一项模棱两可的任务,即从各种 Visual FoxPro 表格中自动提取数据。

有几对.DBF 和.CDX 文件。使用 Python dbf包,我似乎可以和他们一起工作。我有两个文件,ABC.DBF 和 ABC.CDX。我可以使用加载表文件,

>>> 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

我需要做的就是读书。我看到存在四个类,Idx、Index、IndexFile 和 IndexLocation。这些似乎是不错的候选人。

Idx 类读入一个表和文件名,这是有前途的。

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

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

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

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

请您参考如下方法:

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

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

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) 

然后遍历索引而不是表:

for record in my_index: 
    ...