表数据文件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执行以下的语 ...
随机推荐
- robotframework数据驱动框架
即将更新...............
- GT-n8000平板开机密码忘记 解决办法
开机密码忘记了 1: 关机 (不需要连接电脑) 2: 音量上 开机键 一起按住 别松手 直至 进入 英文界面 Android system recovery <3e> 备注:音量键方向错误 ...
- winston日志管理3
Further Reading 延伸阅读 Events and Callbacks in Winston winston的事件和回调 Each instance of winston.Logger i ...
- 第八篇 SQL Server安全数据加密
本篇文章是SQL Server安全系列的第八篇,详细内容请参考原文. Relational databases are used in an amazing variety of applicatio ...
- 发布自己的nuget包;报错source parameter was not specified
16-10-27 VS下使用 程序包管理器控制台 运行: 1.cd 命令走到 工程文件夹下,使用 ls 命令查看当前目录: 2. 使用 nuget spec 创建: 3. 使用 nuget pack ...
- VMware设置共享文件夹
第一步:安装vmware-tools
- Visual Studio 编译纯 C 项目的方法
项目属性 -> 配置属性 -> C/C++ -> 高级 -> 编译为 -> 选择 `编译为C代码(/TC)` 参考资料: http://stackoverflow.com ...
- swift NSUserDefaults的基本使用
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: ...
- TOM大叔的几道Javascript题目与解答
几道JS题目 之前没有深入研究js语言,最近几年前端越来越工程化,需要扎实的js基础,看到博客园上有很多大牛分享JS学习文章,幸运看到tom大叔的blog,抽时间潜心学习了其文章,遇到到其出的几道题目 ...
- MVC 自定义过滤器/特性来实现登录授权及验证
最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精 最近在做自学MVC,遇到的问题很多,索性一点点总结 ...