Created
April 14, 2015 19:06
-
-
Save billspat/2b18fc1c947d6548bf9f to your computer and use it in GitHub Desktop.
simplistic conversion of DBF to CSV. See docstring in code for usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
"""dbf2csv.py | |
DRAFT 4/14/2015 PS Bills, ICER | |
example python code to read DBF and write to standard CSV. | |
Requires dbfread python package installed ( http://dbfread.readthedocs.org ) | |
and Python 2.7 or greater | |
Example usage : | |
python dbconvert.py MYFILE.DBF | |
will write the DBF contents to the screen | |
OR | |
python dbconvert.py -o mynewfile.csv MYFILE.DBF | |
will write to the file mynewfile.csv (erasing the contents first) | |
OR | |
python dbconvert.py -o mynewfile.csv -n MYFILE.DBF | |
will write the dbf to mynwefile.csv but without the field name header row | |
""" | |
import sys,csv, os | |
import argparse | |
from dbfread import DBF | |
def dbf2csv(dbfFilePath,csvFilePath=None,noheader=False): | |
"""given a dbf Filename or Path, and an optional filename for csv output | |
write contents of dbf to CSV format | |
If not outputfilename is given, write to stdout (the screen) | |
csvFilePath must be a single file name (not wildcard) | |
""" | |
table = DBF(dbfFilePath) | |
if(csvFilePath==None): | |
csvfile = sys.stdout | |
else: | |
csvfile = open(csvFilePath, 'w') | |
writer = csv.writer(csvfile) # csv.writer(csvfile) | |
if noheader != True: | |
# double negative | |
# noheader = true, don't write fieldnames, not noheader -> write the fieldnames | |
writer.writerow(table.field_names) | |
for record in table: | |
writer.writerow(list(record.values())) | |
if csvfile != sys.stdout: | |
csvfile.close(); | |
def valid_file(filepath): | |
if not os.path.exists(filepath): | |
msg = "can't find file %s" % filepath | |
raise argparse.ArgumentTypeError(msg) | |
return filepath | |
if __name__ == '__main__': | |
## test for command line argument filenames and send them to the dbf2csv function | |
parser = argparse.ArgumentParser() | |
parser.add_argument('dbfFile', | |
help='dbf file path to convert', | |
type=valid_file ) | |
parser.add_argument('--output', '-o', | |
help='output file for csv', | |
required=False ) | |
parser.add_argument('--noheader', '-n', | |
action='store_true', | |
help='do not make first line of csv the column headings' ) | |
args = parser.parse_args() | |
# if len(sys.argv) < 3: | |
# outputFile = None | |
# else: | |
# outputFile = sys.argv[2] | |
dbf2csv(args.dbfFile, args.output, args.noheader) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment