Copy a column changing the name in Dbf

和自甴很熟 提交于 2019-12-24 06:47:57

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!