Converting a .dbf file to a CSV file

Tim Chase python.list at tim.thechases.com
Thu Nov 2 12:59:20 EST 2006


> Is there a module/method in python to convert a file from .DBF format to
> .CSV format?


Well, at

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362715

there's a recipe for reading DBF files...iterating over the 
returned data from the function declared there, it should be 
pretty easy to simply dump the results to a CSV file...something 
like this untested:

outfile = file('out.txt', 'w')
for i, row in enumerate(dbfreader(file('x.txt'))):
	if i == 1: continue # skip colinfo line
	outfile.write('"')
	outfile.write('","'.join(str(v) for v in row))
	outfile.write('"\n')

Escaping quotes becomes mildly hairier, but only because there 
are a number of ways to do it.  You'd just modify the "str(v)" 
with your escaping function...something like doubling them

	str(v).replace('"', '""')
or
	str(v).replace('\\', '\\\\').replace('"', '\\"')

using backslashes (where standalone-backslashes get escaped too)

Just a few idea,

-tkc






More information about the Python-list mailing list