当前位置:Gxlcms > 数据库问题 > python读写dbf数据库

python读写dbf数据库

时间:2021-07-01 10:21:17 帮助过:119人阅读

读取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数据库

标签:enc   zip   close   encoding   store   领域   删除   很多   field   

人气教程排行