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

  • 相关阅读:
    windows下vagrant使用及工作环境配置
    使用docker搭建lnmp环境
    Docker常用命令
    [docker] 管理docker容器中的数据
    python初始化父类错误
    Linux--
    用少于2MB内存存下5百万个介于0到1千万之间的整数
    k路归并:数组、链表
    剑指offer新思路
    阿里电话面试
  • 原文地址:https://www.cnblogs.com/zhugaopeng/p/9745800.html
Copyright © 2011-2022 走看看