表数据文件DBF的读取和写入操作
import sys
import csv
import struct
import datetime
import decimal
import itertools
from cStringIO import StringIO
from operator import itemgetter def dbfreader(f):
"""Returns an iterator over records in a Xbase DBF file. The first row returned contains the field names.
The second row contains field specs: (type, size, decimal places).
Subsequent rows contain the data records.
If a record is marked as deleted, it is skipped. File should be opened for binary reads. """
# See DBF format spec at:
# http://www.pgts.com.au/download/public/xbase.htm#DBF_STRUCT numrec, lenheader = struct.unpack('<xxxxLH22x', f.read(32))
numfields = (lenheader - 33) // 32 fields = []
for fieldno in xrange(numfields):
name, typ, size, deci = struct.unpack('<11sc4xBB14x', f.read(32))
name = name.replace('\0', '') # eliminate NULs from string
fields.append((name, typ, size, deci))
yield [field[0] for field in fields]
yield [tuple(field[1:]) for field in fields] terminator = f.read(1)
assert terminator == '\r' fields.insert(0, ('DeletionFlag', 'C', 1, 0))
fmt = ''.join(['%ds' % fieldinfo[2] for fieldinfo in fields])
fmtsiz = struct.calcsize(fmt)
for i in xrange(numrec):
record = struct.unpack(fmt, f.read(fmtsiz))
if record[0] != ' ':
continue # deleted record
result = []
for (name, typ, size, deci), value in itertools.izip(fields, record):
if name == 'DeletionFlag':
continue
if typ == "N":
value = value.replace('\0', '').lstrip()
if value == '':
value = 0
elif deci:
value = decimal.Decimal(value)
else:
value = int(value)
elif typ == 'D':
y, m, d = int(value[:4]), int(value[4:6]), int(value[6:8])
value = datetime.date(y, m, d)
elif typ == 'L':
value = (value in 'YyTt' and 'T') or (value in 'NnFf' and 'F') or '?'
elif typ == 'F':
value = float(value)
result.append(value)
yield result def dbfwriter(f, fieldnames, fieldspecs, records):
""" Return a string suitable for writing directly to a binary dbf file. File f should be open for writing in a binary mode. Fieldnames should be no longer than ten characters and not include \x00.
Fieldspecs are in the form (type, size, deci) where
type is one of:
C for ascii character data
M for ascii character memo data (real memo fields not supported)
D for datetime objects
N for ints or decimal objects
L for logical values 'T', 'F', or '?'
size is the field width
deci is the number of decimal places in the provided decimal object
Records can be an iterable over the records (sequences of field values). """
# header info
ver = 3
now = datetime.datetime.now()
yr, mon, day = now.year - 1900, now.month, now.day
numrec = len(records)
numfields = len(fieldspecs)
lenheader = numfields * 32 + 33
lenrecord = sum(field[1] for field in fieldspecs) + 1
hdr = struct.pack('<BBBBLHH20x', ver, yr, mon, day, numrec, lenheader, lenrecord)
f.write(hdr) # field specs
for name, (typ, size, deci) in itertools.izip(fieldnames, fieldspecs):
name = name.ljust(11, '\x00')
fld = struct.pack('<11sc4xBB14x', name, typ, size, deci)
f.write(fld) # terminator
f.write('\r') # records
for record in records:
f.write(' ') # deletion flag
for (typ, size, deci), value in itertools.izip(fieldspecs, record):
if typ == "N":
value = str(value).rjust(size, ' ')
elif typ == 'D':
value = value.strftime('%Y%m%d')
elif typ == 'L':
value = str(value)[0].upper()
else:
value = str(value)[:size].ljust(size, ' ')
assert len(value) == size
f.write(value) # End of file
f.write('\x1A') ###################################################################################3
filename = 'e:/update/shp/test.dbf'
f = open(filename, 'rb')
db = list(dbfreader(f))
f.close()
for record in db:
print record
##### fieldnames is first row means fieldname,fieldspecs is second row means fieldType,records is afterRows means records
fieldnames, fieldspecs, records = db[0], db[1], db[2:] # Remove a field
del fieldnames[0]
del fieldspecs[0]
records = [rec[1:] for rec in records] # Create a new DBF
filename1 ='e:/update/shp/test1.dbf'
f1 = open(filename1, 'wb+')
dbfwriter(f1, fieldnames, fieldspecs, records) # Read the data back from the new DBF
print '-' * 50
f1.seek(0)
for line in dbfreader(f1):
print line
f1.close() # Convert to CSV
print '.' * 50
filename1 ='e:/update/shp/test1.csv'
f1 = open(filename1, 'wb+')
csv.writer(f1).writerow(fieldnames)
csv.writer(f1).writerows(records)
print f1.getvalue()
f1.close()
表数据文件DBF的读取和写入操作的更多相关文章
- Oracle11g数据文件DBF迁移
最近接手了一个以前同事遗留下来的项目,时机比较敏感,因为要召开11届全国少数名族运动会.建国70周年,以及香港暴乱,其中网站上挂载有十几个系统的入口链接,不巧的是其中一个系统存在若口令,被公安部安全局 ...
- Mp3文件标签信息读取和写入(Kotlin)
原文:Mp3文件标签信息读取和写入(Kotlin) - Stars-One的杂货小窝 最近准备抽空完善了自己的星之小说下载器(JavaFx应用 ),发现下载下来的mp3文件没有对应的标签 也是了解可以 ...
- MySQL的奇怪的删表数据文件而表照样能打开
MySQL的奇怪的删表数据文件而表照样能打开 author:headsen chen 2017-11-02 17:57:17 现象:删除一个正在运行的mysql数据库的表的数据文件:* ...
- MySQL实例多库某张表数据文件损坏导致xxx库无法访问故障恢复
一.问题发现 命令行进入数据库实例手动给某张表进行alter操作,发现如下报错. mysql> use xx_xxx; No connection. Trying to reconnect... ...
- MySQL-5.7设置InnoDB表数据文件存储位置
1.表空间 Innodb存储引擎可将所有数据存放于ibdata*的共享表空间,也可将每张表存放于独立的.ibd文件的独立表空间. 共享表空间以及独立表空间都是针对数据的存储方式而言的. 共享表空间: ...
- java文件创建、删除、读取、写入操作大全
一.获得控制台用户输入的信息 public String getInputMessage() throws IOException...{ System.out.println("请输入您的 ...
- 【Python】sasa版:文件中csv读取在写入csv读取的数据和执行是否成功。
sasa写的文件(包含解析文字) # coding=utf- from selenium import webdriver from time import sleep import keyword ...
- Sql server 用T-sql读取本地数据文件dbf的数据文件
第一步启用Ad Hoc Distributed Queries 在SQLserver执行以下的语句: exec sp_configure 'show advanced options',1 reco ...
- win7(64位)Sql server 用T-sql读取本地数据文件dbf的数据文件
原文地址:https://www.cnblogs.com/cl1006/p/9924066.html 第一步启用Ad Hoc Distributed Queries 在SQLserver执行以下的语 ...
随机推荐
- Oracle ORA-12519: TNS:no appropriate service handler found 解决
有时候连得上数据库,有时候又连不上. 可能是数据库上当前的连接数目已经超过了它能够处理的最大值. select count(*) from v$process --当前的连接数select value ...
- winston日志管理2
上次讲到 Exceptions 例外 Handling Uncaught Exceptions with winston 使用winston处理未捕获的异常(这个如果对于异步,我不是很喜欢用) 使用 ...
- SoapUI接口测试·第一个HTTP Request接口请求和断言
一.新建SOAP项目 [File]-[New SOAP Project],在[Project Name]输入{工程名},点击[OK]. 二.新建TestSuite 选中项目,右键选择[New Te ...
- Java native关键字
在String类中 public native String intern(); native关键字是干嘛的? Java不是完美的,Java的不足除了体现在运行速度上要比传统的C++慢许多之外,Jav ...
- javascript设计模式学习之五——策略模式
一.策略模式定义: 定义一些列的算法/规则,将它们封装起来,使得它们可以互相替换/组合使用.其目的在于将算法/规则封装起来,将算法/规则的使用与实现分离出来. 通过策略模式,可以减少算法计算过程中大量 ...
- 在Android平台下的基于Linux-C 的测试程序
iTOP-4412 开发板可以运行的文件系统很多,在具体的文件系统上实现特定功能前,可以 使用Linux-C 程序来测试硬件以及驱动.而且这些程序很容易移植到Android.Qt/E 以及最小文件系统 ...
- Three.js基础探寻十——动画
本篇将介绍如果使用Three.js进行动态画面的渲染.此外,将会介绍一个Three.js作者写的另外一个库stat.js,用来观测每秒帧数(FPS). 1.实现动画效果 1.1 动画原理 对于Thre ...
- ShowMessage和MessageDlg消息对话框(VCL)
ShowMessage一个简单的消息提示: 例如:ShowMessage("xxxx"); MessageDlg(constAnsiString Msg, TMsgDlgType ...
- 01分数规划POJ3621(最优比例生成环)
Sightseeing Cows Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 8218 Accepted: 2756 ...
- Linux 系统结构
Linux的系统结构一般由四部分组成 内核 1)内核 操作系统的核心,具有最基本的功能:内存管理.进程管理.设备驱动管理.文件系统管理,网络管理 内核版本(kernel)查看的三种方法 cat /pr ...