Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中修改dbf文件_Python_Dbf - Fatal编程技术网

如何在Python中修改dbf文件

如何在Python中修改dbf文件,python,dbf,Python,Dbf,假设我在根目录下的一些文件夹中有不同数量的dbf文件,d:\myfolder。dbf文件的内容如下所示: Field1 11110481123 12150480021 ... 我想添加一个字段(例如,Field1),它只包含Field2中值的最后4位 Field1 Field2 11110481123 1123 12150480021 0021 ... ... 然后,我想删除字段1 如何处理Python中分散在不同文件夹中的所有db

假设我在根目录下的一些文件夹中有不同数量的dbf文件,
d:\myfolder
。dbf文件的内容如下所示:

Field1 
11110481123
12150480021
...
我想添加一个字段(例如,
Field1
),它只包含
Field2
中值的最后4位

Field1          Field2
11110481123     1123
12150480021     0021
...             ...
然后,我想删除
字段1


如何处理Python中分散在不同文件夹中的所有dbf文件?

您需要通过pypi(
pip install dbf
)提供名为
dbf
的模块。下面是一个如何在表中添加和删除字段的片段:

import dbf

table = dbf.Table('t1', 'field1 N(12, 0)')
for record in ((11110481123,), (12150480021,)):
    table.append(record)
table.close()

# extend the existing table
dbf.add_fields('t1', 'field2 N(4, 0)')

table = dbf.Table('t1')
records = table.sql('select *')
for record in records:
    record.field2 = int(str(record.field1)[-4:])
table.close()

dbf.delete_fields('t1', 'field1')
尽管只需遍历第一个字段并将其更改为存储其值的最后4位,计算量会减少。

使用上述(加上我的其他库,),但以下(大致)是您将采取的步骤:

# untested

import dbf
from antipathy import Path

for path, dirs, files in Path.walk('.'):
    files = [f for f in files if f.ext == '.dbf']
    for db in files:
        if I_want_to_change_this_table(db):
            with dbf.Table(db) as db:
                db.add_fields('Field2 C(4)')
                for record in db:
                    dbf.write(Field2=record.Field1[-4:])
                db.delete_fields('Field1')
                db.pack()
I\u want\u to\u change\u this\u table()
是一个函数,如果您不想更改每个表,只想更改其中的一些表,则可以使用它。如果您想更改所有记录,可以删除该行。

对于((11110481123,),(12150480021,))中的记录:这里,如果我有很多记录,如何获取这些记录。我想我不能把所有的记录都打出来。