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

标签 python dbf

我正在尝试打开 en 将多个 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: 语法无效

关于如何解决这个问题有什么建议吗?

最佳答案

尝试使用 my dbf library :

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()

关于python - 在 python 中打开 DBF 文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57215656/

相关文章:

python - Pandas 测量自条件以来耗时

python - Django 使用外键进行多个查询

python - 列表字典的笛卡尔积 - 带排序

python - 将 .CSV 转换为 .DBF(dBASEIII) VFP 6.0,一切都变成备注字段

c# - 替换 64 位机器中 dbf 文件的 Jet.OLEDB.4.0 驱动程序

python - 为什么 Selenium 返回一个空文本字段?

python - scipy.lfilter 的替代品

mysql - 将数据从本地计算机上的 dbf 文件持续导入 MySQL 的最简单方法

c# - 在 .Net Winform 应用程序中使用 DBF 数据库

java - DANS DBF 数字类型用法