How can I parse a formatted file into variables using Python?
Question: I have a pre-formatted text file with some variables in it, like this:

    
    
    header one
       name = "this is my name"
       last_name = "this is my last name"
       addr = "somewhere"
       addr_no = 35
    header
    header two
       first_var = 1.002E-3
       second_var = -2.002E-8
    header 
    

As you can see, each score starts with the string `header` followed by the
name of the scope (one, two, etc.).

I can't figure out how to programmatically parse those options using Python so
that they would be accesible to my script in this manner:

    
    
    one.name = "this is my name"
    one.last_name = "this is my last name"
    two.first_var = 1.002E-3
    

Can anyone point me to a tutorial or a library or to a specific part of the
docs that would help me achieve my goal?


Answer: I'd parse that with a generator, yielding sections as you parse the file.
`ast.literal_eval()` takes care of interpreting the value as a Python literal:

    
    
    import ast
    
    def load_sections(filename):
        with open(filename, 'r') as infile:
            for line in infile:
                if not line.startswith('header'):
                    continue  # skip to the next line until we find a header
    
                sectionname = line.split(None, 1)[-1].strip()
                section = {}
                for line in infile:
                    if line.startswith('header'):
                        break  # end of section
                    line = line.strip()               
                    key, value = line.split(' = ', 1)
                    section[key] = ast.literal_eval(value)
    
                yield sectionname, section
    

Loop over the above function to receive `(name, section_dict)` tuples:

    
    
    for name, section in load_sections(somefilename):
        print name, section
    

For your sample input data, that results in:

    
    
    >>> for name, section in load_sections('/tmp/example'):
    ...     print name, section
    ... 
    one {'last_name': 'this is my last name', 'name': 'this is my name', 'addr_no': 35, 'addr': 'somewhere'}
    two {'first_var': 0.001002, 'second_var': -2.002e-08}
    

