固定宽度文件和字符分隔文件写入器/解析器
项目描述
gocept.recordserialize发行版
固定宽度文件和字符分隔文件的写入器/解析器。
此软件包与Python 2.7版本兼容。
固定宽度格式
通过列出所有字段并按顺序定义格式。每个字段有以下设置
- name:
字段名称(必需)
- width:
字段字符宽度(必需)
- fill character:
默认:空格
- alignment:
默认:左对齐(即在右侧填充)
例如
>>> from gocept.recordserialize import FixedWidthRecord >>> class FixedExample(FixedWidthRecord): ... ... encoding = 'utf-8' ... lineterminator = '\r\n' ... ... fields = [ ... ('one', 3, ' ', FixedWidthRecord.LEFT), ... ('two', 7, '0', FixedWidthRecord.RIGHT), ... ]
写入
>>> r = FixedExample() >>> r['one'] = 'foo' >>> r['two'] = '12' >>> str(r) 'foo0000012\r\n'
读取
>>> r = FixedExample.parse('bar0000034\r\n') >>> r['one'] u'bar' >>> r['two'] u'34'
也可用: parse_file,它接受一个文件对象。
字符分隔格式
通过在类上声明属性来定义格式。每个字段有以下设置
- position:
字段位置
- default:
默认值,如果没有给定任何值则写入此值
- 最大长度:
截断字段到这个长度
注意,您不必声明所有字段,未声明的任何位置都用空列填充。因此,您始终需要在 fields 属性中给出字段的总数
>>> from gocept.recordserialize import SeparatedRecord >>> class PipeExample(SeparatedRecord): ... ... fields = 5 ... encoding = 'utf-8' ... separator = '|' ... lineterminator = '\r\n' ... ... first = 1 ... default = 2, 'qux' ... maxlen = 3, 3 ... maxlen_default = 4, 5, 'asdfg'
写入
>>> r = PipeExample() >>> r['first'] = 'some text' >>> r['maxlen'] = '12345' >>> str(r) 'some text|qux|123|asdfg|\r\n'
读取
>>> r = PipeExample.parse('some text|qux|123|asdfg|\r\n') >>> r['first'] u'some text' >>> r['default'] u'qux' >>> r['maxlen'] u'123' >>> r['maxlen_default'] u'asdfg'
也可用: parse_file,它接受一个文件对象。
转义
对于子类化,SeparatedRecord 提供了类方法 escape 和 unescape,每个值在写入/读取时都会通过这些方法。一个利用此功能的示例是 gocept.recordserialize.CSVRecord,它会转义引号
>>> from gocept.recordserialize import CSVRecord >>> class CSVExample(CSVRecord): ... ... fields = 1 ... one = 1 >>> r = CSVExample() >>> r['one'] = 'my "quoted" string' >>> str(r) '"my \'quoted\' string"\r\n'
开发 gocept.recordserialize
gocept.recordserialize 的变更日志
1.0 (2017-12-06)
添加对 setuptools >= 32 的支持。
停止支持 Python 2.6。
0.3 (2016-02-29)
在错误时转义 Unicode 字符。
0.2 (2013-11-26)
修正对 setuptools 的依赖。
0.1 (2012-09-19)
初始发布
项目详情
下载文件
下载适合您平台文件的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。
源代码分发
gocept.recordserialize-1.0.tar.gz (11.0 kB 查看哈希值)
关闭
gocept.recordserialize-1.0.tar.gz 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | ef66a416ec4d04aa55e89e78ccbed33749d04a1608ef5174910f14a3dc1c96f1 |
|
MD5 | de7f5843d23fa1fa97a213f053957ec2 |
|
BLAKE2b-256 | 642ba7a987244271af8eb69f20880369189a2a3045a64c6685ed4f39948c38c9 |