pythonparsingedi

Writing/parsing text file with fixed width lines


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 file, with certain "chunks" of the field with data and others left blank. I have the documentation so I know what the length of each "chunk" is. The response that I get back is easier to parse since it will already have data and I can use Python's "slices" to extract what I need, but I can't assign to a slice - I tried that already because it sounded like a good solution, and it didn't work since Python strings are immutable :)

Like I said I'm really a newbie to Python but I'm excited about learning it :) How would I go about doing this? Ideally I'd want to be able to say that range 10-20 is equal to "Foo" and have it be the string "Foo" with 7 additional whitespace characters (assuming said field has a length of 10) and have that be a part of the larger 80-character field, but I'm not sure how to do what I'm thinking.


Solution

  • You don't need to assign to slices, just build the string using % formatting.

    An example with a fixed format for 3 data items:

    >>> fmt="%4s%10s%10s"
    >>> fmt % (1,"ONE",2)
    '   1       ONE         2'
    >>> 
    

    Same thing, field width supplied with the data:

    >>> fmt2 = "%*s%*s%*s"
    >>> fmt2 % (4,1, 10,"ONE", 10,2)
    '   1       ONE         2'
    >>> 
    

    Separating data and field widths, and using zip() and str.join() tricks:

    >>> widths=(4,10,10)
    >>> items=(1,"ONE",2)
    >>> "".join("%*s" % i for i in zip(widths, items))
    '   1       ONE         2'
    >>>