dbfファイルはpythonを使ってプログラムを読みます.

5773 ワード

  • 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