Writing/parsing a fixed width file using Python

前端 未结 8 1738
清歌不尽
清歌不尽 2020-12-14 11:01

I\'m a newbie to Python and I\'m looking at using it to write some hairy EDI stuff that our supplier requires.

Basically they need an 80-character fixed width text f

8条回答
  •  盖世英雄少女心
    2020-12-14 11:38

    I know this thread is quite old, but we use a library called django-copybook. It has nothing to do with django (anymore). We use it to go between fixed width cobol files and python. You create a class to define your fixed width record layout and can easy move between typed python objects and fixed width files:

    USAGE:
    class Person(Record):
        first_name = fields.StringField(length=20)
        last_name = fields.StringField(length=30)
        siblings = fields.IntegerField(length=2)
        birth_date = fields.DateField(length=10, format="%Y-%m-%d")
    
    >>> fixedwidth_record = 'Joe                 Smith                         031982-09-11'
    >>> person = Person.from_record(fixedwidth_record)
    >>> person.first_name
    'Joe'
    >>> person.last_name
    'Smith'
    >>> person.siblings
    3
    >>> person.birth_date
    datetime.date(1982, 9, 11)
    

    It can also handle situations similar to Cobol's OCCURS functionality like when a particular section is repeated X times

提交回复
热议问题