Tuesday, August 31, 2010

Converting dbf to csv with Python

I wanted something in the ArcGIS toolbox that I could use to convert a dbf to a csv. I didn't see anything already there, and the scripts I found in the ESRI forums seemed needlessly complicated, so I wrote this little one and added it as a new script tool with two inputs of type File. The first one is an Input and is the dbf filename. The second one is an Output and is the csv filename.

This script uses the dbfpy module from http://dbfpy.sourceforge.net/.

import csv
from dbfpy import dbf
import sys

dbf_fn = sys.argv[1]
csv_fn = sys.argv[2]

in_db = dbf.Dbf(dbf_fn)
out_csv = csv.writer(open(csv_fn, 'wb'))

names = []
for field in in_db.header.fields:
    names.append(field.name)
out_csv.writerow(names)

for rec in in_db:
    out_csv.writerow(rec.fieldData)

in_db.close()

1 comments:

  1. Had a similar problem and solved it with PERL and DBI:XBase:

    http://blog.dev001.net/post/14563495366/converting-dbf-to-csv-files

    ReplyDelete