user319487
user319487

Reputation:

Error when trying to convert dbf to csv in Python

Python newbie here so please be gentle.

I'm trying to convert dbf file to csv. I stumbled upon a previous, similar question (with opposite conversion though) and was thinking abou using dbf module.

Using example from the docs I tried this code:

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)

When I try to run it I get the following error:

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'

Why does the export fail?


Update:

As suggested by chm I now use:

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

This still causes problem:

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

Upvotes: 3

Views: 3291

Answers (1)

prehistoricpenguin
prehistoricpenguin

Reputation: 6326

I find that the doc on the site is wrong.If you use help in your code,you can see the right doc as below:

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 now is not a member of class Table. Just use dbf.export(in_db, csv_fn, header=True) instead of in_db.export(filename=csv_fn, header=True)

2.use open after create table (code sample:)

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)

Upvotes: 4

Related Questions