dbf文件怎么打开(python读写dbf数据库)dbf数据库作为一种简单的数据库,曾经广泛使用。现在在金融领域还是有很多的应用之处,工作中遇到此类的问题,在此记录一下。

1. 读取dbf

'''

读取DBF文件

'''

def readDbfFile(filename):

table = dbfread.DBF(filename, encoding='GBK')

for field in table.fields:

print(field)

for record in table:

for field in record:

print(field, record[field])

for delete_record in table.delete:

print(delete_record)

需要倒入外部库:

import dbfread

代码解释:

上面的例子分别读取了dbf的列头,全部的记录和删除的记录

此方法,python2.x和python3.x都是通用的。

2. 写dbf

'''

写DBF文件

@filename 文件名

@header 列头

@content 内容

'''

def writeDbfFile(filename, header, content):

# 打开dbf

db = dbf.Dbf(filename, new=True)

# 写列头

for field in header:

# 此处需要改成长度可配的,长度太短会导致数据被截断

if type(field) == unicode:

field = field.encode('GBK')

db.addField((field, 'C', 20))

# 写数据

for record in content:

rec = db.newRecord()

for key, value in itertools.izip(header, record):

if type(value) == unicode:

rec[key] = value.encode('GBK')

else:

rec[key] = value

rec.store()

# 关闭文档

db.close()

需要的外部库:

from dbfpy import dbf

代码解释:

写dbf的步骤,先新建一个dbf文件,先写入列头,然后每次新增一条记录,写入记录;最后关闭dbf文件。

此方法python2.x可用

标签: python, dbf

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐