码迷,mamicode.com
首页 > 数据库 > 详细

dbf文件使用python读取程序

时间:2015-07-04 00:53:06      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:python   dbf   

  • 使用python读取dbf
# -*- coding: utf-8 -*-
import struct,csv,datetime
class DBF_Operator():
    @staticmethod
    def SHHQ_dbf_reader(f):
        numrec, lenheader = struct.unpack(‘<xxxxLH22x‘, f.read(32))    
        numfields = (lenheader - 33) // 32

        fields = []
        for fieldno in xrange(numfields):
            name, typ, size, deci = struct.unpack(‘<11sc4xBB14x‘, f.read(32))
            name = name.replace(‘\0‘, ‘‘)       # eliminate NULs from string   
            fields.append((name, typ, size, deci))

        terminator = f.read(1)
        assert terminator == ‘\r‘

        fields.insert(0, (‘DeletionFlag‘, ‘C‘, 1, 0)) 
        fmt = ‘‘.join([‘%ds‘ % fieldinfo[2] for fieldinfo in fields])
        fmtsiz = struct.calcsize(fmt)
        result = []#(stock,S3)
        #suspend_result = []
        for i in xrange(numrec):
            record = struct.unpack(fmt, f.read(fmtsiz))
            flag = record[0]
            stock = record[1]
            if stock == "000000":
                pass
            elif stock[0] == ‘6‘ and flag == ‘ ‘:
                result.append((record[1],record[3]))
        return result

    @staticmethod
    def SZHQ_dbf_reader(f):
        numrec, lenheader = struct.unpack(‘<xxxxLH22x‘, f.read(32))    
        numfields = (lenheader - 33) // 32

        fields = []
        for fieldno in xrange(numfields):
            name, typ, size, deci = struct.unpack(‘<11sc4xBB14x‘, f.read(32))
            name = name.replace(‘\0‘, ‘‘)       # eliminate NULs from string   
            fields.append((name, typ, size, deci))

        terminator = f.read(1)
        assert terminator == ‘\r‘

        fields.insert(0, (‘DeletionFlag‘, ‘C‘, 1, 0)) 
        fmt = ‘‘.join([‘%ds‘ % fieldinfo[2] for fieldinfo in fields])
        fmtsiz = struct.calcsize(fmt)
        result = []#(stock,S3)
        for i in xrange(numrec):
            record = struct.unpack(fmt, f.read(fmtsiz))
            flag = record[0]
            stock = record[1]
            if stock == "000000":
                pass
            elif (stock[0] == ‘0‘ or stock[:3] == ‘300‘) and flag == ‘ ‘:
                result.append((record[1],record[3]))
        return result

版权声明:本文为博主原创文章,未经博主允许不得转载。

dbf文件使用python读取程序

标签:python   dbf   

原文地址:http://blog.csdn.net/berguiliu/article/details/46747477

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!