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. CentOS7|RHEL忘记root密码

    某一服务器长时间不使用,或者由于频繁修改root密码,导致忘记root密码无法登陆系统问题,通过进入单用户修改root密码,CentOS7|RHEL7与6系列有一些区别,不在适用于7. 1.在启动gr ...

  2. T4自动生成数据库C#实体类学习(1)

    第一个测试的Demo <#@ template language="C#" debug="True" hostspecific="True&qu ...

  3. D3D9 GPU Hacks (转载)

    D3D9 GPU Hacks I’ve been trying to catch up what hacks GPU vendors have exposed in Direct3D9, and tu ...

  4. IOS Suppot Font 苹果默认支持的字体一览(配图)

    这些字体都是IOS设备(使用ipad2测试) 默认支持的字体,也就是在AIR中不用设置绑定字体情况下 看到的样子 感觉上应该IOS仅为中文设置了一种字体就是 Heiti SC

  5. JAVA多线程与多进程

    并发与并行是两个既相似而又不相同的概念,但往往容易混为一谈,这两者究竟有什么区别呢?本文通过一个例子让你更好地理解(本文由并发编程网翻译). 现代社会是并行的:多核.网络.云计算.用户负载,并发技术对 ...

  6. HUD 5086 Revenge of Segment Tree(递推)

    http://acm.hdu.edu.cn/showproblem.php?pid=5086 题目大意: 给定一个序列,求这个序列的子序列的和,再求所有子序列总和,这些子序列是连续的.去题目给的第二组 ...

  7. [转] JAVA多线程和并发基础面试问答

    JAVA多线程和并发基础面试问答 原文链接:http://ifeve.com/java-multi-threading-concurrency-interview-questions-with-ans ...

  8. HDFS简介

    Hadoop是当今最为流行的大数据分析和处理工具. 其最先的思想来源于Google的三篇论文:                            GFS(Google File System):是 ...

  9. 玩转HTML5移动页面(动效篇)(转载)

    本文转载自: 玩转HTML5移动页面(动效篇)

  10. oracle的例程

    oracle只有在具备sysoper和sysdba权限下才能启动和关闭例程 关闭例程: --正常关闭(等待当前连接的所有用户与数据库断开) shutdown normal; --立即关闭(回退活动的事 ...