python的dbf操作

看网上有dbfread 和 dbfpy 还有dbf几个库,都试着玩一下,暂时发现 dbf库有一直更新,但是还是没法真正删除一行数据。头大。



#!/usr/bin/python
# -- coding: utf-8 --
import datetime
import dbf
'''
【管理员】 
1、删除下sjsjg 文件里面 jgywlb='GSTC' 的数据   
2、重启程序、重启BP所在的服务器
3、重新从第一步开始往后处理
(这个数据处理有问题,后面修改)
'''
dbf_name = 'SJSJG12.DBF'
# create an in-memory table
table1 = dbf.Table(r'D:/python_project/'+dbf_name)
'''
        filename='test',
        field_specs='name C(25); age N(3,0); birth D; qualified L',
        on_disk=False,
        )
        qtsljs446.921
'''
#打印dbf文件属性。
print(table1.status)
print(table1.structure())
#FieldnameList(['GBSCDM C(2)', 'GBLB C(2)', 'GBDM1 C(30)', 'GBDM2 C(30)', 'GBDM3 C(30)', 'GBSL N(25,2)', 'GBRQ1 C(8)', 'GBRQ2 C(8)', 'GBBL N(25,13)', 'GBJE1 N(25,3)', 'GBJE2 N(25,3)', 'GBZD C(100)', 'GBBZ1 C(1)', 'GBBZ2 C(1)', 'GBBZSM C(100)', 'GBSL2 N(25,2)', 'GBBL2 N(25,13)', 'GBRQ3 C(8)', 'GBRQ4 C(8)', 'GBRQ C(8)']) 其中N(25,13) 不支持25这么长的数据
table1.open(dbf.READ_WRITE)
titles = dbf.get_fields('D:/python_project/'+dbf_name) # 将表头以列表形式打印出来
print(titles)
'''
# add some records to it
for datum in (
        ('Spanky', 7, dbf.Date.fromymd('20010315'), False),
        ('Spunky', 23, dbf.Date(1989,7,23), True),
        ('Sparky', 99, dbf.Date(), dbf.Unknown),
        ):
#增加数据
    table.append(datum)
#删除数据
    table.

# iterate over the table, and print the records
for record in table:
    print(record)
    #print('--------')
    #print(record[0:15])
    #print([record.name, record.age, record.birth])
    #print(record[0],"table is delete?:",is_deleted(record))
    print('--------')
'''
#print(table1) 数据太多不要打印

# make a copy of the test table (structure, not data)
custom = table1.new(
        filename='new'+dbf_name,
        default_data_types=dict(C=dbf.Char, D=dbf.Date, L=dbf.Logical),
        )

# automatically opened and closed
with custom:
    # copy records from test to custom
    i = 0
    j = 0
    for record in table1:
        if (record.jgzqdm[0:6]=='116016'): #这里处理数据
            j= j+1                  
        else:
            i= i+1
            custom.append(record)
    print("新文件数据数量:"+str(i)+'----减少了的数据数量:'+str(j))
'''#数据太多不要打印
    # modify each record in custom (could have done this in prior step)
    for record in custom:
        dbf.write(record, name=record.name.upper())
        # and print the modified record
        print(record)
        print('--------')
        print(record[0:3])
        print([record.name, record.age, record.birth])
        print('--------')
'''
print(custom.status)
table1.close()


修改成功的实例

import time
import shutil
import dbf

source_dir = r'C:\jhui'
destination_dir = r'C:\jhui'

"""DBF修改任务"""
os.chdir(destination_dir)
#for file in os.listdir(destination_dir):
file=destination_dir+'\\bc900214.b15'
tb = dbf.Table(destination_dir+'\\bc900214.b15')  # 创建tb实例
# print(tb) # 打印tb信息
titles = dbf.get_fields(file)  # 将表头以列表形式打印出来
print(titles)
if 'JYRQ' in titles:
    flag = 0  # 文件修改标记
    tb.open(mode=dbf.READ_WRITE)  # 读写方式打开tb
    for record in tb:
        with record as r:
            if r.JYRQ is not None:
                # print(r.dealstat)
                r.JYRQ = '20211116'
                r.QSRQ = '20211116'
                r.JSRQ = '20211118'
                flag = 1  # 修改后将标记改为1
                # print(r.dealstat)
            else:
                continue
        
    tb.close()
    if flag == 0:
        print(file + "===>>>没有要修改的数据!\n")
    else:
        print(file + "===>>>JYRQ字段修改完毕!\n")
else:
    print(file + "===>>>没有JYRQ字段!\n")

print('INFO ===>>> 今日文件修改完毕!\n')
#两个dbf文件合并到一个dbf文件里面去。
import os,sys
import datetime
import dbf
import time

def hebing(filename1,filename2):
        # create an in-memory table
    table1 = dbf.Table(filename=filename1)
    table1.open()
    table2 = dbf.Table(filename=filename2)
    table2.open()
    custom = table1.new(
            filename= filename1+"_rzrq.dbf",
            default_data_types=dict(C=dbf.Char, D=dbf.Date, L=dbf.Logical),
            )
    # 读写方式打开dbf文件dbf.READ_ONLY or dbf.READ_WRITE
    custom.open(dbf.READ_WRITE)
    i=0
    j=0
    jj=0
    for record2 in table2:
        print(record2.JGWTXH) #打印其中一个JGWTXH字段内容
        custom.append(record2)
        jj = jj+1
        if jj > 6 :
             break;
    for record in table1:
        custom.append(record)
        i = i+1
    for record2 in custom:
        b=datetime.timedelta(days=1)
        dbf.write(record2, JGCJRQ=record2.JGCJRQ+b)
        dbf.write(record2, JGFSRQ=record2.JGFSRQ+b)#修改文件1内容
        j=j+1
        if j>6:
            break;
    print("总共数据:"+str(i+jj))

    custom.close()
    print(custom.status)
    table1.close()
    table2.close()
if __name__ == '__main__':

    hebing(r'.\BJSJG24.DBF',r'.\BJSJG23.DBF')
  • 最近读取dbf文件里面的中文出现报错:
    UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xb9 in position 2: ordinal not in range(128)
    我不理解 dbf文件是 ascii编码的 为什么可以出现中文。
    阅读官方测试文档,看看灵感。
    C:\Program Files\Python37\Lib\site-packages\dbf\test.py

    bkup = Table(
    new_name, self.structure(), memo_size,
    codepage=self.codepage.name,
    dbf_type=self._versionabbr,
    on_disk=on_disk,
    )

codepage是编码的可以有[cp936(中文) , utf8 ascii ] 等等 看__init__.py 的codepage

import dbf
table = dbf.Table(filename='.\SZYH_SJSGB0511.dbf',codepage='cp936')
table.open()
print(table.status)
for row in table:
    print(row)
table.close()
---没有报错了。
  • 另外一个思路
    发现一个博主对dbf文件的总结。
    pdfpy python2.x 可以对DBF文件进行写入
    dbfread python2.x/3.x 可以对DBF文件的读取,删除
    xlwt python2.x/3.x 可以对DBF文件进行写入
    openpyxl python2.x/3.x 不可以对DBF文件进行读取
    xlrd python2.x/3.x 不可以对DBF文件进行读取
    xlsxwriter python2.x/3.x 还没试
    ————————————————
    原文链接:https://blog.csdn.net/weixin_43992799/article/details/106727700

使用
dbfread 库读写是没问题的。

from dbfread import DBF
# f = open('SZYH_SJSGB0512.DBF', encoding='gbk',errors="ignore")
table = DBF('SZYH_SJSGB0512.DBF',encoding='gbk')
#遍历数据表中(没加删除标志)的记录
index=1
for record in table:
    print(index)
    #for field in record:
        #print(field, "=", record[field], end=",")
    print(record)
    print('\n')

    index+=1

  • 4
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值