Parse each line by character location

Tim Chase python.list at tim.thechases.com
Tue Nov 4 12:29:23 EST 2008


> I hope this is the right place to ask, but I am trying to come up with
> a way to parse each line of a file. Unfortunately, the file is neither
> comma, nor tab, nor space delimited. Rather, the character locations
> imply what field it is.
> 
> For example:
> 
> The first ten characters would be the record number, the next
> character is the client type, the next ten characters are a volume,
> and the next three are order type, and the last character would be an
> optional type depending on the order type.

Sounds like you could do something like

   recno_idx = slice(0,10)
   client_idx = slice(10, 11)
   volume_idx = slice(11,11+10)
   order_type_idx = slice(11+10, 11+10+3)

   out = file('out.txt', 'w')
   for line in file('in.txt'):
     out.write(','.join([
       s[recno_idx],
       s[client_idx],
       s[volume_idx],
       s[order_type_idx],
       s[11+10+3:],
       ]))
   out.close()

-tkc







More information about the Python-list mailing list