Sunday, August 25, 2013

Batch conversion of .dbf to .csv in Python

Batch conversion of .dbf to .csv in Python

I have ~300 folders with 9 .dbf files and 2 non .dbf files. I am trying to
use os.walk to find all .dbf files in a folder and then a for loop to
convert each .dbf file to a .csv file. I don't need to touch the non .dbf
files.
I was able to do a single file conversion with the dbfpy module but am
having issues scaling it up to a batch process.
My code below is based on code from here.
import csv
from dbfpy import dbf
import os
path = r"\Documents\House\DBF"
destpath = r"\Documents\House\CSV"
for root, dirnames, filenames in os.walk(path):
for filename in filenames:
if filename.endswith('.DBF'):
dbf.Dbf(filename)
out_csv = csv.writer(open(filename[:-4]+csv, 'wb'))
names = []
for field in filename.header.fields:
names.append(field.name)
out_csv.writerow(names)
for rec in filename:
out_csv.writerow(rec.fieldData)
filename.close()
I am getting the following error on the first .dbf file found:
mdr dbf.DBF
Traceback (most recent call last):
File "C:\Users\Stephen\workspace\convertDBF\src\xml2csv.py", line 13, in
<module>
dbf.Dbf(filename)
File "C:\Anaconda\lib\site-packages\dbfpy\dbf.py", line 125, in __init__
self.stream = file(f, ("r+b", "rb")[bool(readOnly)])
IOError: [Errno 2] No such file or directory: 'mdr dbf.DBF'
It's saying the file is in use in Python. I am not just concerned about
this error as I believe the code has greater issues beyond this.

No comments:

Post a Comment