Python 3 dbfread读写dbf 文件的时候,float 类型字段解析错误

传送门

dbfread GitHub 项目地址

Python读取dbf文件,转化为Pandas DataFrame

问题描述
  • 在用python读取一个dbf文件时发现有个字段不能正确解析,在调用DBF类的时候
table = DBF(r'D:\Projects\Repo 3\task_files\20191212\dbzqqyfaC17.dbf')
table.fields

发现其中一个 字段的 field 长度解析错误

DBFField(name='blfz2', type='N', address=179, length=17, decimal_count=12, reserved1=0, workarea_id=0, reserved2=0, reserved3=0, set_fields_flag=0, reserved4=b'\x00\x00\x00\x00\x00\x00\x00', index_field_flag=0)
DBFField(name='blfm2', type='C', address=196, length=3072, decimal_count=0, reserved1=0, workarea_id=0, reserved2=0, reserved3=0, set_fields_flag=0, reserved4=b'\x00\x00\x00\x00\x00\x00\x00', index_field_flag=0)

这样导致接下来读取 records 的时候,不能正常解析 数据。用excel 打开dbf文件发现 blfm2 其实是 float类型的数据,但是在dbf文件里却被 错误 定义成了 字符类型 ( ‘C’ type)
在这里插入图片描述

  • 在查看了源代码后发现问题出在了 dbf.py 里 DBF 类的一个方法定义上,当遇到 ‘C’ (character) 类型的字段时,会去修改 field.length, field.decimal_count, 但这并不是我们想要的结果。
解决办法
  • 将源代码里的部分代码注释掉,如下所示,亲测可行
def _read_field_headers(self, infile):
    while True:
        sep = infile.read(1)
        if sep in (b'\r', b'\n', b''):
            # End of field headers
            break

        field = DBFField.unpack(sep + infile.read(DBFField.size - 1))

        field.type = chr(ord(field.type))
        # 有些字段会出现定义错误,所以把这段注释掉了
        # For character fields > 255 bytes the high byte
        # is stored in decimal_count.
        # if field.type in 'C':
        #     field.length |= field.decimal_count << 8
        #     field.decimal_count = 0

        # Field name is b'\0' terminated.
        field.name = self._decode_text(field.name.split(b'\0')[0])
        if self.lowernames:
            field.name = field.name.lower()

        self.field_names.append(field.name)

        self.fields.append(field)
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值