Python - Convert CSV to DBF

11,216

Duplicate question at: Convert .csv file into .dbf using Python?

Promising answer there (among others) is Use the csv library to read your data from the csv file. The third-party dbf library can write a dbf file for you.

Share:
11,216
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I would like to convert a csv file to dbf using python (for use in geocoding which is why I need the dbf file) - I can easily do this in stat/transfer or other similar programs but I would like to do as part of my script rather than having to go to an outside program. There appears to be a lot of help questions/answers for converting DBF to CSV but I am not having any luck the other way around.

    An answer using dbfpy is fine, I just haven't had luck figuring out exactly how to do it.

    As an example of what I am looking for, here is some code I found online for converting dbf to csv:

    import csv,arcgisscripting
    from dbfpy import dbf
    
    gp = arcgisscripting.create()
    
    try:
        inFile = gp.GetParameterAsText(0) #Input
        outFile = gp.GetParameterAsText(1)#Output
        dbfFile = dbf.Dbf(open(inFile,'r'))
        csvFile = csv.writer(open(outFile, 'wb'))
        headers = range(len(dbfFile.fieldNames))
        allRows = []
        for row in dbfFile:
            rows = []
            for num in headers:
                rows.append(row[num])
            allRows.append(rows)
        csvFile.writerow(dbfFile.fieldNames)
        for row in allRows:
            print row
            csvFile.writerow(row)
    except:
        print gp.getmessage()
    

    It would be great to get something similar for going the other way around.

    Thank you!