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的读取和写入操作的更多相关文章

  1. Oracle11g数据文件DBF迁移

    最近接手了一个以前同事遗留下来的项目,时机比较敏感,因为要召开11届全国少数名族运动会.建国70周年,以及香港暴乱,其中网站上挂载有十几个系统的入口链接,不巧的是其中一个系统存在若口令,被公安部安全局 ...

  2. Mp3文件标签信息读取和写入(Kotlin)

    原文:Mp3文件标签信息读取和写入(Kotlin) - Stars-One的杂货小窝 最近准备抽空完善了自己的星之小说下载器(JavaFx应用 ),发现下载下来的mp3文件没有对应的标签 也是了解可以 ...

  3. MySQL的奇怪的删表数据文件而表照样能打开

    MySQL的奇怪的删表数据文件而表照样能打开 author:headsen  chen      2017-11-02   17:57:17 现象:删除一个正在运行的mysql数据库的表的数据文件:* ...

  4. MySQL实例多库某张表数据文件损坏导致xxx库无法访问故障恢复

    一.问题发现 命令行进入数据库实例手动给某张表进行alter操作,发现如下报错. mysql> use xx_xxx; No connection. Trying to reconnect... ...

  5. MySQL-5.7设置InnoDB表数据文件存储位置

    1.表空间 Innodb存储引擎可将所有数据存放于ibdata*的共享表空间,也可将每张表存放于独立的.ibd文件的独立表空间. 共享表空间以及独立表空间都是针对数据的存储方式而言的. 共享表空间: ...

  6. java文件创建、删除、读取、写入操作大全

    一.获得控制台用户输入的信息 public String getInputMessage() throws IOException...{ System.out.println("请输入您的 ...

  7. 【Python】sasa版:文件中csv读取在写入csv读取的数据和执行是否成功。

    sasa写的文件(包含解析文字) # coding=utf- from selenium import webdriver from time import sleep import keyword ...

  8. Sql server 用T-sql读取本地数据文件dbf的数据文件

    第一步启用Ad Hoc Distributed Queries  在SQLserver执行以下的语句: exec sp_configure 'show advanced options',1 reco ...

  9. win7(64位)Sql server 用T-sql读取本地数据文件dbf的数据文件

    原文地址:https://www.cnblogs.com/cl1006/p/9924066.html 第一步启用Ad Hoc Distributed Queries  在SQLserver执行以下的语 ...

随机推荐

  1. 追加文件内容java

    1.向空文件文件中追加内容(如果原来有内容,则覆盖) FileWriter writer; try { writer = new FileWriter(listFile);//创建字符输出流类对象和已 ...

  2. Linux就这个范儿 第11章 独霸网络的蜘蛛神功

    Linux就这个范儿 第11章  独霸网络的蜘蛛神功  第11章 应用层 (Application):网络服务与最终用户的一个接口.协议有:HTTP FTP TFTP SMTP SNMP DNS表示层 ...

  3. 在CDialog::OnInitDialog设置DEFAULT-BUTTON的注意事项

    如果你的Dialog是在资源编辑器里面创建的,那么你首先要去资源编辑器把对应的Button的Default Button选项设置为True 另外,如果你使用GotoDlgCtrl,那么记得OnInit ...

  4. TOMCAT 关闭报错:Tomcat did not stop in time. PID file was not removed

    关闭tomcat的时候,报出如下错误信息: # ./shutdown.sh Using CATALINA_BASE: /opt/openkm-6.3.1-community/tomcat Using ...

  5. PDB重命名

    PDB重命名 将PDB clonedb重命名为rdb SQL> select name,open_mode from v$pdbs; NAME OPEN_MODE --------------- ...

  6. Android Log图文详解

    android.util.Log常用的方法有以下5个:Log.v() Log.d() Log.i() Log.w() 以及 Log.e() .根据首字母对应VERBOSE,DEBUG,INFO, WA ...

  7. Dive into python 实例学python (2) —— 自省,apihelper

    apihelper.py def info(object, spacing=10, collapse=1): """Print methods and doc strin ...

  8. PostgreSQL Replication之第十二章 与Postgres-XC一起工作(2)

    12.2安装 Postgres-XC 可以从 http://postgres-xc.sourceforge.net/下载Postgres-XC.对于本书,我们使用1.0.3版本的Postgres-XC ...

  9. CSS禅意花园(设计一)

    设计 1.排版样式. 正文部分文字比例比菜单不分班的大,可区分着两个区域(说明正文比菜单重要).排版也是一种交流方式,运用文字的大小.间距.颜色调整样式,给浏览者丰富的信息. 2.图标 3.分割线 适 ...

  10. php setcookie(name, value, expires, path, domain, secure) 参数详解

    setcookie() 定义一个和其余的 HTTP 标头一起发送的 cookie.和其它标头一样,cookie 必须在脚本的任何其它输出之前发送(这是协议限制).这 需要将本函数的调用放到任何输出之前 ...