zoukankan      html  css  js  c++  java
  • 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可用

  • 相关阅读:
    sdibt 1251 进化树问题
    hdu 2014 位运算
    poj 3254 状态压缩dp
    hdu 5040bfs+优先队列 需要存状态
    zoj 3812 状压dp
    C++标准库:bitset 用法整理&&zoj 3812
    BZOJ 2572 高速公路
    BZOJ 1036 树的统计
    BZOJ 1035 Risk
    BZOJ 1034 泡泡堂
  • 原文地址:https://www.cnblogs.com/zhugaopeng/p/9745800.html
Copyright © 2011-2022 走看看