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可用

  • 相关阅读:
    CF1042E Vasya and Magic Matrix
    Luogu 4868 Preprefix sum
    CF1042F Leaf Sets
    CF1041F Ray in the tube
    【Luogu】P1410子序列(DP)
    【Luogu】P1383高级打字机
    【Luogu】P1681最大正方形2(异或运算,DP)
    【Luogu】P1122最大子树和(DFS,树上DP)
    【Luogu】P2258子矩阵(状态压缩,DP)
    【Luogu】P2158仪仗队(欧拉函数)
  • 原文地址:https://www.cnblogs.com/zhugaopeng/p/9745800.html
Copyright © 2011-2022 走看看