4

假设我在根目录下的某些文件夹中有不同数量的 dbf 文件,d:\myfolder. dbf 文件的内容如下所示:

Field1 
11110481123
12150480021
...

我想添加一个Field1仅包含Field2.

Field1          Field2
11110481123     1123
12150480021     0021
...             ...

然后,我想删除Field1.

如何为分散在 Python 中不同文件夹中的所有 dbf 文件完成这项工作?

4

2 回答 2

4

您需要dbf通过 pypi ( pip install dbf) 调用的模块。以下是如何从表中添加和删除字段的片段:

import dbf

table = dbf.Table('t1', 'field1 N(12, 0)')
for record in ((11110481123,), (12150480021,)):
    table.append(record)
table.close()

# extend the existing table
dbf.add_fields('t1', 'field2 N(4, 0)')

table = dbf.Table('t1')
records = table.sql('select *')
for record in records:
    record.field2 = int(str(record.field1)[-4:])
table.close()

dbf.delete_fields('t1', 'field1')

尽管仅遍历第一个字段并对其进行更改以存储其值的最后 4 位数字会减少计算量。

于 2012-05-05T14:44:45.170 回答
1

使用上面提到的dbf 库(加上我的另一个库antipathy),这些是(大致)您将采取的步骤:

# untested

import dbf
from antipathy import Path

for path, dirs, files in Path.walk('.'):
    files = [f for f in files if f.ext == '.dbf']
    for db in files:
        if I_want_to_change_this_table(db):
            with dbf.Table(db) as db:
                db.add_fields('Field2 C(4)')
                for record in db:
                    dbf.write(Field2=record.Field1[-4:])
                db.delete_fields('Field1')
                db.pack()

I_want_to_change_this_table()如果您不想更改每个表,只需更改其中的一些表,这是您提供的功能。如果您想更改它们,您可以删除该行。

于 2016-03-31T00:26:03.727 回答