Parsing a YAML file in Python, and accessing the data ?

Parsing a YAML file in Python, and accessing the data ?

Asked on January 9, 2019 in XML.
Add Comment


  • 6 Answer(s)

         The function yaml.load() that belongs to PyYAML’s will parses YAML documents to native Python data structures, simply we can access items by key or the index. Use the example:

    import yaml
    with open('tree.yaml', 'r') as f:
       doc = yaml.load(f)
    

         To access branch1 text use,

    txt = doc["treeroot"]["branch1"]
    print txt
    "branch1 text"
    

    because, in our YAML document, the value of the branch1 key is under the treeroot key.

    Answered on January 9, 2019.
    Add Comment

    How do I access the text “branch1 text”?

    YAML parsing and Python?” provides a solution, but I had problems accessing the data from a more complex YAML file. And, I’m wondering if there is some standard way of accessing the data from a parsed YAML file, possibly something similar to “tree iteration

    Answered on February 25, 2019.
    Add Comment
    ### Script to modify YAML file by taking a parameter
    import sys  #### To do File input output operations
    from ruamel.yaml import YAML #To create YAML File and Read YAML File
    inp_fo = open("data.yml").read()  ## Read the Yaml File
    yaml = YAML() ## Load the yaml object
    code = yaml.load(inp_fo) #Load content of YAML file to yaml object
    code['notifications']['email']['recipients'] = [sys.argv[1]] #Update
    Yaml file with new parameter in object
    inp_fo2 = open("data.yml","w") #Open the file for Write
    yaml.dump(code,inp_fo2) ##Write to file with new parameter
    inp_fo2.close() #close the file
    Answered on February 25, 2019.
    Add Comment
    reactor:
      diameter_inner: 2.89 cm
      temperature: 773 kelvin
      gas_mass_flow: 1.89 kg/s
    
    biomass:
      diameter: 2.5 mm                # mean Sauter diameter (1)
      density: 540 kg/m^3             # source unknown
      sphericity: 0.89 unitless       # assumed value
      thermal_conductivity: 1.4 W/mK  # based on value for pine (2)
    
    catalyst:
      density: 1200 kg/m^3                            # from MSDS sheet
      sphericity: 0.65 unitless                       # assumed value
      diameters: [[86.1, 124, 159.03, 201], microns]  # sieve screen diameters
      surface_areas:
        values:
          - 12.9
          - 15
          - 18
          - 24.01
          - 31.8
          - 38.51
          - 42.6
        units: square micron
    Answered on February 25, 2019.
    Add Comment
    import yaml
    
    
    class Reactor:
    
        def __init__(self, rdict):
            self.diameter_inner = float(rdict['diameter_inner'].split()[0])
            self.temperature = float(rdict['temperature'].split()[0])
            self.gas_mass_flow = float(rdict['gas_mass_flow'].split()[0])
    
    
    class Biomass:
    
        def __init__(self, bdict):
            self.diameter = float(bdict['diameter'].split()[0])
            self.density = float(bdict['density'].split()[0])
            self.sphericity = float(bdict['sphericity'].split()[0])
    
    
    class Catalyst:
    
        def __init__(self, cdict):
            self.diameters = cdict['diameters'][0]
            self.density = float(cdict['density'].split()[0])
            self.sphericity = float(cdict['sphericity'].split()[0])
            self.surface_areas = cdict['surface_areas']['values']
    
    
    class Parameters:
    
        def __init__(self, file):
    
            with open(file, 'r') as f:
                params = yaml.safe_load(f)
    
            # reactor parameters
            rdict = params['reactor']
            self.reactor = Reactor(rdict)
    
            # biomass parameters
            bdict = params['biomass']
            self.biomass = Biomass(bdict)
    
            # catalyst parameters
            cdict = params['catalyst']
            self.catalyst = Catalyst(cdict)

     

    Answered on February 25, 2019.
    Add Comment
    from params import Parameters
    
    pm = Parameters('params.yaml')
    
    # reactor
    d_inner = pm.reactor.diameter_inner
    temp = pm.reactor.temperature
    mf_gas = pm.reactor.gas_mass_flow
    
    # biomass
    d_bio = pm.biomass.diameter
    rho_bio = pm.biomass.density
    
    # catalyst
    rho_cat = pm.catalyst.density
    sp_cat = pm.catalyst.sphericity
    d_cat = pm.catalyst.diameters
    sa_cat = pm.catalyst.surface_areas
    
    print('\n--- Reactor Parameters ---')
    print(f'd_inner = {d_inner}')
    print(f'temp = {temp}')
    print(f'mf_gas = {mf_gas}')
    
    print('\n--- Biomass Parameters ---')
    print(f'd_bio = {d_bio}')
    print(f'rho_bio = {rho_bio}')
    
    print('\n--- Catalyst Parameters ---')
    print(f'rho_cat = {rho_cat}')
    print(f'sp_cat = {sp_cat}')
    print(f'd_cat = {d_cat}')
    print(f'sa_cat = {sa_cat}')

     

    Answered on February 25, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.