Python3读写dbf文本
安装环境
pip install dbf
关于dbf的文档可以在一下网址了解dbf文档(https://pythonhosted.org/dbf/)
还有github的地址(https://github.com/ethanfurman/dbf/tree/master/dbf)
操作示例与介绍
- 把现有的dbf文件的数据,copy到一个指定的模板里面,建议此方式
'''
把现有的dbf文件的数据,copy到一个指定的模板里面,并填充新增的项
'''
import dbf
src_filename = 'xxxx\\test.DBF' #原dbf的地址
des_filename = 'xxxx\\template.DBF' #期望得到的dbf模板
# create an in-memory table
table = dbf.Table(
filename=des_filename, #打开模板文件
codepage='cp936', #相当于gbk的方式打开
on_disk=True, #是否在磁盘上保存修改
)
table.open(mode=dbf.READ_WRITE) #让内存中的table以可读写的方式打开,默认为只读
#同上 以只读的方式打开原dbf
src_table = dbf.Table(
filename=src_filename,
codepage='cp936',
)
src_table.open()
for i in src_table:
#这里的i并不是一个列表,而是一个数据结构,可以通过以下的方式转化为列表
record_len = len(i)
one_data_list = i[0:record_len] + ['00','']
one_data = tuple(one_data_list)
table.append(record)
#当然 你也可以自己添加新的一行数据 如下
new_record = (1, '1', '测试', '20200831', '20200831', '1', '', '00', '')
table.append(new_record)
#可以用下面的方式,读取
for record in table:
print(record)
print('--------')
print(record[0:9])
print([record.HGSQXH, record.HGZQZH, record.HGZHMC])
print('--------')
src_table.close()
table.close() #关闭并保存到磁盘
- 新建一个新的格式的dbf,笔者目前没有实际使用场景,在此给出说明文档给的示例,为了方便运行,做了一些修改。
import datetime
import dbf
# create an in-memory table
table = dbf.Table(
filename='test',
field_specs='name C(25); age N(3,0); birth D; qualified L',
on_disk=False,
)
table.open(mode=dbf.READ_WRITE)
# add some records to it
for datum in (
('Spanky', 7, dbf.Date.fromymd('20010315'), False),
('Spunky', 23, dbf.Date.fromymd('20010315'), True),
('Sparky', 99, dbf.Date(), dbf.Unknown),
):
table.append(datum)
# iterate over the table, and print the records
for record in table:
print(record)
print('--------')
print(record[0:3])
print([record.name, record.age, record.birth])
print('--------')
# make a copy of the test table (structure, not data)
custom = table.new(
filename='test_on_disk',
default_data_types=dict(C=dbf.Char, D=dbf.Date, L=dbf.Logical),
)
# automatically opened and closed
with custom:
# copy records from test to custom
for record in table:
custom.append(record)
# modify each record in custom (could have done this in prior step)
for record in custom:
dbf.write(record, name=record.name.upper())
# and print the modified record
print(record)
print('--------')
print(record[0:3])
print([record.name, record.age, record.birth])
print('--------')
table.close()