简体   繁体   中英

Adding Values inside DBF field using Python

I want to create a dbf file and then add fields and values to it using python. I can create the dbf file and fields but don't know how to excatly add the values inside the corresponding fields. 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. 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.

#
# 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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