固定宽度和字符分隔文件的文件编写器/分析器
gocept.recordserialize的Python项目详细描述
gocept.recordserialize发行版
固定宽度和字符分隔文件的文件编写器/分析器。
这个包与Python2.7版本兼容。
固定宽度格式
通过按顺序列出所有字段来定义格式。每个字段都有以下内容 设置:
name: | Name of the field (required) |
---|---|
width: | Width of the field in characters (required) |
fill character: | default: Space |
alignment: | default: align LEFT (that is, pad on the right side) |
例如:
>>> 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: | position of the field |
---|---|
default: | default value to write if none is given |
maximum length: | truncate field to this length |
注意,您不必声明所有字段,任何未声明的位置都是 填充空列。因为这个原因,你总是要给出 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
Author: | gocept <mail@gocept.com> |
---|---|
PyPI page: | https://pypi.org/project/gocept.recordserialize/ |
Issue tracker: | https://bitbucket.org/gocept/gocept.recordserialize/issues |
Source code: | https://bitbucket.org/gocept/gocept.recordserialize/ |
gocept.recordserialize的更改日志
1.0(2017-12-06)
- 添加对setuptools=32的支持。
- 放弃对Python2.6的支持。
0.3(2016-02-29)
- 错误时转义unicode字符
0.2(2013-11-26)
- 修复了对setuptools的依赖性。
0.1(2012-09-19)
初次发行