简体   繁体   English

使用 Python 在 DBF 字段内添加值

[英]Adding Values inside DBF field using Python

I want to create a dbf file and then add fields and values to it using python.我想创建一个 dbf 文件,然后使用 python 向它添加字段和值。 I can create the dbf file and fields but don't know how to excatly add the values inside the corresponding fields.我可以创建 dbf 文件和字段,但不知道如何在相应字段中精确添加值。 I have a huge dataset to perform this operation on, which is why I am using the loop.我有一个巨大的数据集来执行这个操作,这就是我使用循环的原因。 Here is just a sample of what the data would be like.这只是数据的示例。 With this code, the dbf is created and fields are added but not the values inside those fields.使用此代码,会创建 dbf 并添加字段,但不会添加这些字段中的值。 Any help would be appreciated.任何帮助,将不胜感激。

import dbf
dctClmVal ={'a':'19', 'b':'76', 'c':'59', 'd':}    
lstFields = ['a','b','c','d']
out_dbf_Path= r"C:\Users\ms\Stats\new.dbf"

db=dbf.Table(out_dbf_Path)
db.open(mode= dbf.READ_WRITE)
for clm in lstFields:
    db.add_fields( clm + " C(50)")

for field in lstFields:
    if(field.upper() in db.field_names):
        db.append({'field=dctClmVal[field]'})
db.close()

After cleaning up your code a little, what you need is something like this:稍微清理一下代码后,您需要的是这样的:

import dbf

records = ({'a':'19', 'b':'76', 'c':'59', }, )

lstFields = ['a C(50)','b C(50)','c C(50)','d C(50)']
out_dbf_Path= "new.dbf"

db = dbf.Table(out_dbf_Path, lstFields)
db.open(mode=dbf.READ_WRITE)

for dctClmVal in records:
    db.append(dctClmVal)

db.close()

and to read what you written:并阅读您所写的内容:

>>> with db:
...   print db[0]
... 

  0 - a         : u'19                                                '
  1 - b         : u'76                                                '
  2 - c         : u'59                                                '
  3 - d         : u'                                                  '

From comment:来自评论:

if my dictionary has values in list format corresponding to each key, Example:如果我的字典具有与每个键对应的列表格式的值,例如:

records = {
        'a': ['2','4','6'],
        'b': ['3','5','7'],
        'c': ['8','9','0'],
        }

How can I update my db?如何更新我的数据库?

That are much better ways to store your records than having an individual record's fields spread across different lists.与将单个记录的字段分布在不同列表中相比,这是存储记录更好的方法。 If one list is corrupted it could affect every succeeding row.如果一个列表被破坏,它可能会影响每一行。

Note: I removed the ()s from records as they weren't doing anything.注意:我从records删除了 ()s,因为它们没有做任何事情。

#
# combine into individual records
#
real_records = []
for field, values in records.items():
    for i, value in enumerate(values):
        if len(real_records) == i:
            real_records.append({})
        real_records[i][field] = value
#
# now add to db
#
for record in real_records:
    db.append(record)

I hope that helps with your understanding.我希望这有助于您的理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM