如何使用dbfpy获取字段类型?

时间:2013-02-28 23:55:08

标签: python types dbf

我有一些我要添加新字段的dbf文件。为此,我使用dbfpy打开原始dbf,复制所有字段(或我想保留的字段)和记录,然后使用这些字段和我想要的新字段创建一个新文件。一切都很好,除了一个小细节:我无法保留原始字段的类型,因为我不知道如何获取它们。我正在做的是将新文件中的所有字段创建为“C”(字符),到目前为止,我现在需要的是这些字段,但最终可能是个问题。

真正的问题是没有可用的文档。我搜索了包文件以查找那里的例子,但找不到这个问题的答案(可能是我找不到的只是“绿色”我仍然使用python ...我绝对是不是专家)。

代码示例:

from dbfpy import dbf
import sys

org_db_file = str(sys.argv[1])
org_db = dbf.Dbf(org_db_file, new = False)

new_db_file = str(sys.argv[2])
new_db = dbf.Dbf(new_db_file, new = True)

#Obtain original field names:
fldnames = []
fldsize = {}
for names in org_db.fieldNames:
  fldnames.append(names)
  fldsize[name] = 0

#Cycle thru table entries:
for rec in org_db:

  #Cycle thru columns to obtain fields' name and value:
  for name in fldnames:
    value = str(rec[name])
    if len(value) > fldsize[name]:
      fldsize[name] = len(value)

#Copy original fields to new table:
for names in fldnames:
  new_db.addField((names, "C", fldsize[name]))

#Add new fields:
new_fieldname = "some_name"
new_db.addField((new_fieldname, "C", 2))

#Copy original entries and store new values:
for rec in org_db:

  #Create new record instance for new table:
  new_rec = new_db.newRecord()

  #Populate fields:
  for field in fldnames:
    new_rec[field] = rec[field]

  #Store value of new field for record i:
  new_rec[new_fieldname] = "some_value"
  new_rec.store()    

new_db.close()

提前感谢您的时间。 欢呼声。

1 个答案:

答案 0 :(得分:1)

我没有任何dbfpy经验,除了几年前我第一次看到它(以及其他几个)不能满足我的需求。 So I wrote my own.

以下是使用它完成任务的方法:

import dbf
import sys

org_db_file = sys.argv[1]
org_db = dbf.Table(org_db_file)

new_db_file = sys.argv[2]
# postpone until we have the field names...
# new_db = dbf.Dbf(new_db_file, new = True)

# Obtain original field list:
fields = org_db.field_names
for field in fields[:]:  # cycle through a separate list
    if field == "something we don't like":
        fields.remove(field)

# now get definitions for fields we keep
field_defs = ord_db.structure(fields)

# Add new fields:
field_defs.append("some_name C(2)")

# now create new table
new_db = ord_db.new(new_db_file, field_specs=field_defs)

# open both tables
with dbf.Tables(ord_db, new_db):

    # Copy original entries and store new values:
    for rec in org_db:

        # Create new record instance for new table:
        new_db.append()

        # Populate fields:
        with new_db.last_record as new_rec:
            for field in new_db.field_names:
                new_rec[field] = rec[field]

                # Store value of new field for record i:
                new_rec[new_fieldname] = "some_value"