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

6 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
  2. Thanks for sharing, found this very helpful!

    ReplyDelete
  3. Thanks, worked perfectly!

    Just for remembering users the usage of the script:

    import csv
    from dbfpy import dbf
    import sys

    if(len(sys.argv) < 2):
    print "Error: Missing arguments.\n\tUsage: python dbf2csv.py in_dbf_file out_csv_filename"
    exit (1)

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

    ReplyDelete
  4. Each record is separated by a delimiter such as a comma or a semi colon and every new row of data indicates a new record.excel dashboard software

    ReplyDelete