在python中打开DBF文件时出现问题


问题内容

我正在尝试打开并将几个DBF文件转换为一个数据框。它们中的大多数都能正常工作,但是对于其中一个文件,我收到错误消息:“
UnicodeDecodeError:’utf-8’编解码器无法解码位置15的字节0xf6:无效的起始字节”

我已经在其他一些主题(例如,打开csv和xlsx等文件)上阅读了此错误。提议的解决方案是encoding = 'utf-8'
在读取文件部分中包括该部分。不幸的是,我还没有找到DBF文件的解决方案,并且我对DBF文件的了解非常有限。

到目前为止我尝试过的是:

1)

from dbfread import DBF
dbf = DBF('file.DBF')
dbf = pd.DataFrame(dbf)

UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 8: character maps to <undefined>

2)

from simpledbf import Dbf5
dbf = Dbf5('file.DBF')
dbf = dbf.to_dataframe()

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 15: invalid start byte

3)

# this block of code copied from https://gist.github.com/ryan-hill/f90b1c68f60d12baea81 
import pysal as ps

def dbf2DF(dbfile, upper=True): #Reads in DBF files and returns Pandas DF
    db = ps.table(dbfile) #Pysal to open DBF
    d = {col: db.by_col(col) for col in db.header} #Convert dbf to dictionary
    #pandasDF = pd.DataFrame(db[:]) #Convert to Pandas DF
    pandasDF = pd.DataFrame(d) #Convert to Pandas DF
    if upper == True: #Make columns uppercase if wanted 
        pandasDF.columns = map(str.upper, db.header) 
    db.close() 
    return pandasDF

dfb = dbf2DF('file.DBF')

AttributeError: module 'pysal' has no attribute 'open'

最后,如果我尝试安装dbfpy模块,则会收到:SyntaxError:语法无效

关于如何解决这个问题的任何建议?


问题答案:

尝试使用我的dbf图书馆

import dbf

table = dbf.Table('file.DBF')

打印它以查看文件中是否存在编码:

print table    # print(table) in Python 3

我的测试表之一如下所示:

    Table:         tempy.dbf
    Type:          dBase III Plus
    Codepage:      ascii (plain ol ascii)
    Status:        DbfStatus.CLOSED
    Last updated:  2019-07-26
    Record count:  1
    Field count:   2
    Record length: 31 
    --Fields--
      0) name C(20)
      1) desc M

重要的是该Codepage行-听起来好像DBF文件没有正确设置。如果知道应该是什么,则可以使用以下代码页(临时)打开它:

table = dbf.Table('file.DBF', codepage='...')

或者,您可以使用以下命令永久更改(更新DBF文件):

table.open()
table.codepage = dbf.CodePage('cp1252') # for example
table.close()