python读写dbf文件

python读写dbf文件,第1张

概述python读写dbf文件

下面是内存溢出 jb51.cc 通过网络收集整理的代码片段。

内存溢出小编现在分享给大家,也给大家做个参考。

读取遍历dBASE或Xbase文件中的记录。从Python的序列创建DBF文件。
import struct,datetime,decimal,itertoolsdef dbfreader(f):    """Returns an iterator over records in a Xbase DBF file.    The first row returned contains the fIEld names.    The second row contains fIEld specs: (type,size,decimal places).    Subsequent rows contain the data records.    If a record is marked as deleted,it is skipped.    file should be opened for binary reads.    """    # See DBF format spec at:    #     http://www.pgts.com.au/download/public/xbase.htm#DBF_STRUCT    numrec,lenheader = struct.unpack('<xxxxLH22x',f.read(32))        numfIElds = (lenheader - 33) // 32    fIElds = []    for fIEldno in xrange(numfIElds):        name,typ,deci = struct.unpack('<11sc4xBB14x',f.read(32))        name = name.replace('','')       # eliminate Nuls from string           fIElds.append((name,deci))    yIEld [fIEld[0] for fIEld in fIElds]    yIEld [tuple(fIEld[1:]) for fIEld in fIElds]    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)    for i in xrange(numrec):        record = struct.unpack(fmt,f.read(fmtsiz))        if record[0] != ' ':            continue                        # deleted record        result = []        for (name,deci),value in itertools.izip(fIElds,record):            if name == 'DeletionFlag':                continue            if typ == "N":                value = value.replace('','').lstrip()                if value == '':                    value = 0                elif deci:                    value = decimal.Decimal(value)                else:                    value = int(value)            elif typ == 'D':                y,m,d = int(value[:4]),int(value[4:6]),int(value[6:8])                value = datetime.date(y,d)            elif typ == 'L':                value = (value in 'YyTt' and 'T') or (value in 'NnFf' and 'F') or '?'            elif typ == 'F':                value = float(value)            result.append(value)        yIEld resultdef dbfwriter(f,fIEldnames,fIEldspecs,records):    """ Return a string suitable for writing directly to a binary dbf file.    file f should be open for writing in a binary mode.    FIEldnames should be no longer than ten characters and not include \x00.    FIEldspecs are in the form (type,deci) where        type is one of:            C for ascii character data            M for ascii character memo data (real memo fIElds not supported)            D for datetime objects            N for ints or decimal objects            L for logical values 'T','F',or '?'        size is the fIEld wIDth        deci is the number of decimal places in the provIDed decimal object    Records can be an iterable over the records (sequences of fIEld values).        """    # header info    ver = 3    Now = datetime.datetime.Now()    yr,mon,day = Now.year-1900,Now.month,Now.day    numrec = len(records)    numfIElds = len(fIEldspecs)    lenheader = numfIElds * 32 + 33    lenrecord = sum(fIEld[1] for fIEld in fIEldspecs) + 1    hdr = struct.pack('<BBBBLHH20x',ver,yr,day,numrec,lenheader,lenrecord)    f.write(hdr)                          # fIEld specs    for name,(typ,deci) in itertools.izip(fIEldnames,fIEldspecs):        name = name.ljust(11,'\x00')        fld = struct.pack('<11sc4xBB14x',name,deci)        f.write(fld)    # terminator    f.write('\r')    # records    for record in records:        f.write(' ')                        # deletion flag        for (typ,value in itertools.izip(fIEldspecs,record):            if typ == "N":                value = str(value).rjust(size,' ')            elif typ == 'D':                value = value.strftime('%Y%m%d')            elif typ == 'L':                value = str(value)[0].upper()            else:                value = str(value)[:size].ljust(size,' ')            assert len(value) == size            f.write(value)    # End of file    f.write('\x1A')# -------------------------------------------------------# Example callsif __name__ == '__main__':    import sys,csv    from cStringIO import StringIO    from operator import itemgetter    # Read a database    filename = '/pydev/databases/orders.dbf'          if len(sys.argv) == 2:        filename = sys.argv[1]    f = open(filename,'rb')    db = List(dbfreader(f))    f.close()    for record in db:        print record    fIEldnames,records = db[0],db[1],db[2:]    # Alter the database    del records[4]    records.sort(key=itemgetter(4))    # Remove a fIEld    del fIEldnames[0]    del fIEldspecs[0]    records = [rec[1:] for rec in records]    # Create a new DBF    f = StringIO()    dbfwriter(f,records)    # Read the data back from the new DBF    print '-' * 20        f.seek(0)    for line in dbfreader(f):        print line    f.close()    # Convert to CSV    print '.' * 20        f = StringIO()    csv.writer(f).writerow(fIEldnames)        csv.writer(f).writerows(records)    print f.getvalue()    f.close()# Example Output"""['ORDER_ID','CUSTMR_ID','EMPLOY_ID','ORDER_DATE','ORDER_AMT'][('C',10,0),('C',11,('D',8,('N',12,2)]['10005     ','WALNG      ','555        ',datetime.date(1995,5,22),Decimal("173.40")]['10004     ','BMARK      ','777        ',18),Decimal("3194.20")]['10029     ','SAWYH      ',6,29),Decimal("97.30")]['10013     ','RITEB      ',2),Decimal("560.40")]['10024     ','RATTC      ','444        ',21),Decimal("2223.50")]['10018     ',12),Decimal("1076.05")]['10025     ',23),Decimal("185.80")]['10038     ','olDWO      ','111        ',7,14),Decimal("863.96")]['10002     ','MTIME      ','333        ',16),Decimal("731.80")]['10007     ','MORNS      ',24),Decimal("1405.00")]['10026     ',26),Decimal("17.40")]['10030     ','liLLO      ',3),Decimal("909.91")]['10022     ','LAPLA      ',19),Decimal("671.50")]['10035     ','HIGHG      ',11),Decimal("1984.83")]['10033     ','FOODG      ',6),Decimal("3401.32")]--------------------['CUSTMR_ID',2)]['MORNS      ',Decimal("17.40")]['SAWYH      ',Decimal("97.30")]['WALNG      ',Decimal("173.40")]['RATTC      ',Decimal("185.80")]['RITEB      ',Decimal("560.40")]['LAPLA      ',Decimal("671.50")]['MTIME      ',Decimal("731.80")]['olDWO      ',Decimal("863.96")]['liLLO      ',Decimal("909.91")]['RATTC      ',Decimal("1076.05")]['MORNS      ',Decimal("1405.00")]['HIGHG      ',Decimal("1984.83")]['BMARK      ',Decimal("3194.20")]['FOODG      ',Decimal("3401.32")]....................CUSTMR_ID,EMPLOY_ID,ORDER_DATE,ORDER_AMTMORNS,555,1995-06-26,17.40SAWYH,777,1995-06-29,97.30WALNG,1995-05-22,173.40RATTC,444,1995-06-23,185.80RITEB,1995-06-02,560.40LAPLA,111,1995-06-19,671.50MTIME,333,1995-05-16,731.80olDWO,1995-07-14,863.96liLLO,1995-07-03,909.91RATTC,1995-06-12,1076.05MORNS,1995-05-24,1405.00HIGHG,1995-07-11,1984.83BMARK,1995-05-18,3194.20FOODG,1995-07-06,3401.32"""

以上是内存溢出(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

总结

以上是内存溢出为你收集整理的python读写dbf文件全部内容,希望文章能够帮你解决python读写dbf文件所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1199074.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存