问题
i have a dbf file with this scruture:
__SAMPLEID
1
2
3
4
I want to copy the values but change na column name, the result i expect is something like that:
__SAMPLEID ID
1 1
2 2
3 3
4 4
i try to use dbfpy or db libs on python, its possible to do that?
回答1:
Using my dbf library:
To rename a field in an existing dbf:
import dbf
with dbf.Table('file-name-here.dbf') as table:
table.rename_field('old_name', 'new_name')
To copy the table, giving a new name to certain fields:
import dbf
old_table = dbf.Table('original-table-here.dbf')
fields = old_table.structure()
# fields is a list of specifications, such as "name C(20)"
changes = [('field1', 'field10'), ('field2', 'field20')]
for old_name, new_name in changes:
for i, f in enumerate(fields):
if f.startswith(old_name + ' '): # note the space!
fields[i] = f.replace(old_name, new_name)
new_table = dbf.Table('new_table_name_here.dbf', fields)
with old_table as old, new_table as new:
for record in old_table:
new_table.append(tuple(record))
来源:https://stackoverflow.com/questions/40474283/copy-a-column-changing-the-name-in-dbf