0

我有一些要添加新字段的 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()

在此先感谢您的时间。干杯。

4

1 回答 1

1

除了几年前我第一次去寻找它(和其他几个)时,我没有任何使用 dbfpy 的经验,它不能满足我的需求。 所以我自己写了。

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

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"
于 2013-03-01T01:36:34.090 回答