传送门
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)