Batch conversion of .dbf to .csv in Python

This is the place for queries that don't fit in any of the other categories.

Batch conversion of .dbf to .csv in Python

Postby 5tanczak » Fri Aug 30, 2013 10:51 pm

I have ~300 folders with .dbf files that I would like to convert to .csv files.

I am using os.walk to find all the .dbf files and then a for loop utilizing the dbfpy module to convert each .dbf file to a .csv.

I am not receiving any errors but the files are not converting (staying as dbf files in path folder). Additionally, the dbf files are being emptied out (reduce to size of 0Kb) after the script is run. Note: the dbf files are stored in a subfolder of the Misc folder below.


Code: Select all
import csv
from dbfpy import dbf
import os

path = r"C:\Users\Stephen\Documents\House\Misc"

for dirpath, dirnames, filenames in os.walk(path):
    for filename in filenames:
        if filename.endswith( '.DBF'):
            csv_fn = filename[:- 4]+ ".CSV"
            with open(csv_fn, 'wb ') as csvfile:
                in_db = dbf.Dbf(os.path.join(dirpath, filename), new= True)
                out_csv = csv.writer(csvfile)

                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)




Any help appreciated....
5tanczak
 
Posts: 3
Joined: Fri Aug 30, 2013 9:46 pm

Re: Batch conversion of .dbf to .csv in Python

Postby stranac » Sat Aug 31, 2013 7:50 am

It looks like passing new=True creates a new, empty .dbf file.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1144
Joined: Thu Feb 07, 2013 3:42 pm

Re: Batch conversion of .dbf to .csv in Python

Postby 5tanczak » Sat Aug 31, 2013 5:15 pm

Thanks! You are exactly right- that is what was emptying out my files. And I realized the conversion code works fine but it was storing the .csv files in my working directory and not my path folder as I was expecting. Rookie Mistake....
5tanczak
 
Posts: 3
Joined: Fri Aug 30, 2013 9:46 pm


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests