我如何改进此 Python 脚本以替换 dbf 文件中的记录?

How could I improve this Python script to replace records in dbf file?

我有一个包含大约 900 万条记录和 2.5 GB 大小的 dbf 文件。 一个 80 大小的字符字段占用了很多 space,用于存储大约 10 个不同字符串中的 1 个。 为了节省文件大小,我想用整数字段替换字符字段,并在以后使用关系数据库来获取完整的字符字段。

目前我有以下 Python 脚本,它使用 dbf 库 (http://pythonhosted.org/dbf/)。该脚本似乎可以正常工作(在较小的 dbf 文件上测试),但是当我尝试使用完整的 dbf 文件 运行 时,它 运行 持续了几个小时。

import dbf

tabel = dbf.Db3Table('dataset.dbf')
tabel.open()

with tabel:
 tabel.add_fields('newfield N(2, 0)')
 for record in tabel:
     if record.oldfield == 'string_a                                                                        ':
         dbf.write(record, newfield=1)
     elif record.oldfield == 'string_b                                                                        ':
         dbf.write(record, newfield=2)
     elif record.oldfield == 'string_c                                                                        ':
         dbf.write(record, newfield=3)
     elif record.oldfield == 'string_d                                                                        ':
         dbf.write(record, newfield=4)
     elif record.oldfield == 'string_e                                                                        ':
         dbf.write(record, newfield=5)
     elif record.oldfield == 'string_f                                                                        ':
         dbf.write(record, newfield=6)
     elif record.oldfield == 'string_g                                                                        ':
         dbf.write(record, newfield=7)
     elif record.oldfield == 'string_h                                                                        ':
         dbf.write(record, newfield=8)
     elif record.oldfield == 'string_i                                                                        ':
         dbf.write(record, newfield=9)
     elif record.oldfield == 'string_j                                                                        ':
         dbf.write(record, newfield=10)
     else:
         dbf.write(record, newfield=0)

dbf.delete_fields('dataset.dbf', 'oldfield')

正如您可能从代码中看到的那样,我对 Python 和 dbf 库都是新手。这个脚本可以更有效地 运行 吗?

添加和删除字段都会先备份您的 2.5GB 文件。

最好的办法是创建一个与原始结构相同的新 dbf,除了这两个字段;然后在复制每条记录时进行更改。类似于:

# lightly untested

old_table = dbf.Table('old_table.dbf')
structure = old_table.structure()
old_field_index = structure.index('oldfield')
structure = structure[:old_field_index] + structure[old_field_index+1:]
structure.append('newfield N(2,0)')
new_table = dbf.Table('new_name_here.dbf', structure)

with dbf.Tables(old_table, new_table):
    for rec in old_table:
        rec = list(rec)
        old_value = rec.pop(old_field_index)
        rec.append(<transform old_value into new_value>)
        new_table.append(tuple(rec))