Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Parsing Fixed-Length File Records with Python

DZone's Guide to

Parsing Fixed-Length File Records with Python

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

I’ve recently had to deal with parsing fixed-length file records and found struct.unpack and namedtuple to be a pretty useful and concise combination for the task:

>>> from struct import unpack
>>> from collections import namedtuple
>>> line = '    23C   17000'
>>> Transaction = namedtuple('Transaction', 'code status amount')
>>> format = '<6sc8s' # code: 6bytes, status: 1byte, amount: 8bytes
>>> txn = Transaction._make(unpack(format, line))
>>> txn
Transaction(code='    23', status='C', amount='   17000')
>>> txn.code, txn.status, txn.amount
('    23', 'C', '   17000')

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}