我写了一个python dbf 模块,它具有非常基本的 SQL 支持。但是,即使 SQL 不能满足您的需求,使用 python 语法查询 dbf 文件也很容易。
一些例子:
import dbf
要创建结果表并向其中添加记录:
results = dbf.Table('results_table', 'name C(50); amount N(10, 4)')
record = results.append()
with record:
record.name = 'something'
record.amount = 99.928
# to open an existing table
table = dbf.Table('some_dbf_table').open()
# find all sales >= $10,000
records = table.pql("select * where sales >= 10000")
# find all transactions for customer names that start with Bob
records = table.pql("select * where customer.startswith('Bob')")
# nevermind thin sql veneer, just use python commands
records = table.find("sales >= 10000 and customer.startswith('Bob')")
# sum sales by customer
customer_sales = default_dict(int) # if customer not already seen, will default to 0
for record in table:
customer_sales[record.customer] += record.sales
# now add to results table and print them out
for name, total in sorted(customer_sales.items()):
result_record = results.append()
with result_record:
result_record.name = name
result_record.amount = total
print "%s: %s" % (name, total)