跳转到主要内容

固定宽度文件和字符分隔文件写入器/解析器

项目描述

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 提供了类方法 escapeunescape,每个值在写入/读取时都会通过这些方法。一个利用此功能的示例是 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 <mail@gocept.com>

PyPI 页面:

https://pypi.ac.cn/project/gocept.recordserialize/

问题跟踪器:

https://bitbucket.org/gocept/gocept.recordserialize/issues

源代码:

https://bitbucket.org/gocept/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 查看哈希值)

源代码

由以下机构支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面