Reading a Python formatted string

I have a file with a series 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

All data is formatted in ASCII format.

Example line:

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

My current thought is that I would like to read the file in a line at a time and somehow break each line into a dictionary so that I can reference the components. Is there any module that does this in Python or some other clean way?

Thank!

+5
source share
3 answers

EDIT . You can still use the struct module:

See the struct module documentation . It looks like you want to usestruct.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)
+14
source

, /, . , Real, Character Integer , . ( , , , ):

format = {}
types = {"Real":float, "Character":str, "Integer":int}

for line in open("format.txt", "r"):
    values = line.split("\t")
    range = values[1].split("-")
    format[values[0]]={"start":int(range[0])-1, "end":int(range[1])-1, "type":types[values[2]]}

results=[]
for line in open("filename.txt"):
    result={}
    for key in format:
        result[key]=format["type"](line[format["start"]:format["end"]])
    results.append(result)

, , .

+1

It looks like you could write a function using strings and slices quite simply. line [0: 5] will be the first element. Does it need to be extensible, or is it probably once?

0
source

All Articles