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. Spring 3.x jar 包详解 与 依赖关系(转)

    以下的内容我会持续更新(当然是我有新发现的时候); 以下内容是我在网上搜索.整理.修改的而成的内容.由于很多内容都是转载了,无法追溯到源头,因此无法一一对原作者进行道谢. 这几天,我查阅大量的官方的文 ...

  2. node.js render模板

    在用node组织前端架构和后端的时候,如果不用nginx做反向代理,则会考虑怎么样render模板. 在现有的项目中没有以下几种方式render模板: 1.将.html当做静态文件,如果url定位到哪 ...

  3. thinkphp 对数据库的操作

    查看ThinkPHP完全开发手册3.1 首先编辑配置文件 thinkphp这个数据库就不乱改了 昨天新建了一个 confluence(utf8)数据库 所以就用它学习一下吧,因为就只建立了一个数据库, ...

  4. [RGeos]手簿

    1.屏幕坐标以像素为单位,地图坐标通常以米为单位,CAD制图默认以毫米为单位. DPI是“dot per inch”的缩写.顾名思义,就是指在每英寸长度内的点数.通常,我们都使用dpi来作为扫描器和打 ...

  5. Java基础之在窗口中绘图——绘制曲线(CurveApplet 1)

    Applet程序. 定义自由曲线的类有两个,其中一个定义二次曲线,另一个定义三次曲线.这些自由曲线是用一系列线段定义的参数化曲线.二次曲线段用方程定义,方程包含独立变量x的平方.三次曲线也用方程定义, ...

  6. #pragma message的作用

    一般情况下,#pragma message( messagestring )是在编译期间,将一个文字串(messagestring)发送到标准输出窗口.典型的使用方法是在编译时报告和显示信息.下面的代 ...

  7. tableview在第一次显示时会自动relodata

    tableview在第一次显示时会自动加载数据

  8. PostgreSQL 中定义自己需要的数据类型

    PostgreSQL解决某系数据库中的tinyint数据类型问题,创建自己需要的数据类型如下: CREATE DOMAIN tinyint AS smallint CONSTRAINT tinyint ...

  9. SQL 数据库备、还,附、分,数据查询,聚合函数

    认识数据库备份和事务日志备份 数据库备份与日志备份是数据库维护的日常工作,备份的目的是在于当数据库出现故障或者遭到破坏时可以根据备份的数据库及事务日志文件还原到最近的时间点将损失降到最低点. 数据库备 ...

  10. 。。。mkdir与mkdirs的区别。。。

    一直想知道他俩的区别,也一直忘记了,知道今天才没有放过这个机会! mkdir的用法是正创建一层目录,比如说在C盘下创建aa文件夹,c:\aa,这个aa是不存在的,这个话,是可以用mkdir创建的,但是 ...