132 |
# work because a DBF file object buffers some data |
# work because a DBF file object buffers some data |
133 |
|
|
134 |
def __init__(self, filename): |
def __init__(self, filename): |
135 |
self.filename = filename |
self.filename = os.path.abspath(filename) |
136 |
|
|
137 |
# Omit the extension in the title as it's not really needed and |
# Omit the extension in the title as it's not really needed and |
138 |
# it can be confusing because dbflib removes extensions and |
# it can be confusing because dbflib removes extensions and |
465 |
|
|
466 |
return name_map |
return name_map |
467 |
|
|
468 |
def table_to_dbf(table, filename): |
def table_to_dbf(table, filename, rows = None): |
469 |
"""Create the dbf file filename from the table""" |
"""Create the dbf file filename from the table. |
470 |
|
|
471 |
|
If rows is not None (the default) then it must be a list of row |
472 |
|
indices to be saved to the file, otherwise all rows are saved. |
473 |
|
""" |
474 |
|
|
475 |
dbf = dbflib.create(filename) |
dbf = dbflib.create(filename) |
476 |
|
|
477 |
dbflib_fieldtypes = {FIELDTYPE_STRING: dbflib.FTString, |
dbflib_fieldtypes = {FIELDTYPE_STRING: dbflib.FTString, |
491 |
dbf.add_field(name_map[col.name], dbflib_fieldtypes[col.type], |
dbf.add_field(name_map[col.name], dbflib_fieldtypes[col.type], |
492 |
width, prec) |
width, prec) |
493 |
|
|
494 |
for i in range(table.NumRows()): |
if rows is None: |
495 |
|
rows = range(table.NumRows()) |
496 |
|
|
497 |
|
recNum = 0 |
498 |
|
for i in rows: |
499 |
record = {} |
record = {} |
500 |
for key, value in table.ReadRowAsDict(i).items(): |
for key, value in table.ReadRowAsDict(i).items(): |
501 |
record[name_map[key]] = value |
record[name_map[key]] = value |
502 |
dbf.write_record(i, record) |
dbf.write_record(recNum, record) |
503 |
|
recNum += 1 |
504 |
dbf.close() |
dbf.close() |
505 |
|
|
506 |
def table_to_csv(table, filename): |
def table_to_csv(table, filename, rows = None): |
507 |
"""Export table to csv file.""" |
"""Export table to csv file. |
508 |
|
|
509 |
|
If rows is not None (the default) then it must be a list of row |
510 |
|
indices to be saved to the file, otherwise all rows are saved. |
511 |
|
""" |
512 |
|
|
513 |
file = open(filename,"w") |
file = open(filename,"w") |
514 |
columns = table.Columns() |
columns = table.Columns() |
519 |
header = header + "\n" |
header = header + "\n" |
520 |
file.write(header) |
file.write(header) |
521 |
|
|
522 |
for i in range(table.NumRows()): |
if rows is None: |
523 |
|
rows = range(table.NumRows()) |
524 |
|
|
525 |
|
for i in rows: |
526 |
record = table.ReadRowAsDict(i) |
record = table.ReadRowAsDict(i) |
527 |
if len(record): |
if len(record): |
528 |
line = "%s" % record[columns[0].name] |
line = "%s" % record[columns[0].name] |