DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > Parsing Fixed-Length File Records with Python

Parsing Fixed-Length File Records with Python

Ruslan Spivak user avatar by
Ruslan Spivak
·
Apr. 21, 12 · Web Dev Zone · Interview
Like (0)
Save
Tweet
6.57K Views

Join the DZone community and get the full member experience.

Join For Free
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')
Record (computer science) Python (language)

Published at DZone with permission of Ruslan Spivak, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Kafka Fail-Over Using Quarkus Reactive Messaging
  • Cloud-Based Integrations vs. On-Premise Models
  • Image Classification Using SingleStore DB, Keras, and Tensorflow
  • Message Queuing and the Database: Solving the Dual Write Problem

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo