Python Read Formatted String
Question: I have a file with a number of lines formatted with the following syntax:

    
    
    FIELD      POSITION  DATA TYPE
    ------------------------------
    COOP ID       1-6    Character
    LATITUDE     8-15    Real
    LONGITUDE   17-25    Real
    ELEVATION   27-32    Real
    STATE       34-35    Character
    NAME        37-66    Character
    COMPONENT1  68-73    Character
    COMPONENT2  75-80    Character
    COMPONENT3  82-87    Character
    UTC OFFSET  89-90    Integer
    

The data is all ASCII-formatted.

An example of a line is:

    
    
    011084  31.0581  -87.0547   26.0 AL BREWTON 3 SSE                  ------ ------ ------ +6
    

My current thought is that I'd like to read the file in a line at a time and
_somehow_ have each line broken up into a dictionary so I can refer to the
components. Is there some module that does this in Python, or some other clean
way?

Thanks!


Answer: **EDIT** : You can still use the struct module:

See the [struct module](http://docs.python.org/library/struct.html)
documentation. Looks to me like you want to use `struct.unpack()`

What you want is probably something like:

    
    
    import struct
    with open("filename.txt", "r") as f:
        for line in f:
            (coop_id, lat, lon, elev, state, name, c1, c2, c3, utc_offset
             ) = struct.unpack("6sx8sx9sx6sx2sx30sx6sx6sx6sx2s", line.strip())
            (lat, lon, elev) = map(float, (lat, lon, elev))
            utc_offset = int(utc_offset)
    

