【问题标题】:Error when trying to convert dbf to csv in Python尝试在 Python 中将 dbf 转换为 csv 时出错
【发布时间】:2012-12-06 08:03:06
【问题描述】:

这里是Python新手,所以请温柔。

我正在尝试将 dbf 文件转换为 csv。我偶然发现了一个previous, similar 问题(尽管有相反的转换),并且正在考虑使用dbf 模块。

使用docs 中的示例我尝试了以下代码:

import dbf

dbf_fn = r'_PATH_HERE_\dbffile.dbf'
csv_fn = r'_PATH_HERE_\csvfile.csv'

in_db = dbf.Table(dbf_fn)

in_db.export(filename=csv_fn, header=True)

当我尝试运行它时,我收到以下错误:

Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    in_db.export(filename=csv_fn, header=True)
  File "C:\Python27\ArcGIS10.1\lib\site-packages\dbf.py", line 3379, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'Db3Table' object has no attribute 'export'

为什么导出失败?


更新:

按照chm 的建议,我现在使用:

dbf.export(in_db, csv_fn, header=True)

这仍然会导致问题:

Traceback (most recent call last):
  File "D:\Data_RP\data\projects\kN\GIS\python\04_convert_dbf_ALT.py", line 31, in <module>
    dbf.export(in_db, filename=csv_fn, header=True)
  File "C:\Python27\ArcGIS10.1\lib\site-packages\dbf.py", line 5670, in export
    table = source_table(table_or_records[0])
  File "C:\Python27\ArcGIS10.1\lib\site-packages\dbf.py", line 3384, in __getitem__
    return self._table[value]
  File "C:\Python27\ArcGIS10.1\lib\site-packages\dbf.py", line 3175, in __getitem__
    raise DbfError("%s is closed; record %d is unavailable" % (meta.filename, index))
DbfError: D:\Data_RP\data\projects\kN\GIS\shapes\SWM_4N.dbf is closed; record 0 is unavailable

【问题讨论】:

    标签: python dbf


    【解决方案1】:

    我发现网站上的文档是错误的。如果您在代码中使用帮助,您可以看到正确的文档如下:

    export(table_or_records, filename, field_names=None,
    format='csv', header=True, codepage=None)
    writes the records using CSV or tab-delimited format, using the filename
    given if specified, otherwise the table name
    if table_or_records is a collection of records (not an actual table) they
    should all be of the same format
    

    1.export 现在不是Table 类的成员。 只需使用 dbf.export(in_db, csv_fn, header=True) 代替 in_db.export(filename=csv_fn, header=True)

    2.创建表后使用open(代码示例:)

    import dbf
    
    csv_fn = r'sdv.csv'
    
    table = dbf.Table('temptable.dbf')
    table.open()
    
    dat=('John Doe', 31)
    table.append(dat)
    dbf.export(table, csv_fn, header = True)
    

    【讨论】:

    • 谢谢。我用了你的建议。不幸遇到了另一个问题:DbfError: D:\Data_RP\data\projects\kN\GIS\shapes\SWM_4N.dbf is closed; record 0 is unavailable。现在是什么问题? o_O
    • 我建议在遇到问题时仔细阅读相关文档。最好的问候!
    猜你喜欢
    • 2021-10-03
    • 2011-04-23
    • 2013-08-28
    • 2020-03-31
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 2020-03-07
    • 2011-05-25
    相关资源
    最近更新 更多