簡體   English   中英

嘗試在python中將dbf轉換為csv時出錯

[英]Error when trying to convert dbf to csv in Python

這里的Python新手,請保持溫柔。

我正在嘗試將dbf文件轉換為csv。 我偶然發現了一個先前的類似問題(盡管轉換相反),並且正在考慮使用dbf模塊。

使用文檔中的示例,我嘗試了以下代碼:

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

我發現網站上的文檔有誤。如果在代碼中使用幫助,則會看到正確的文檔,如下所示:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM