def matches_to_csv()

in tools/cdms/cdms_reader.py [0:0]


def matches_to_csv(matches, csvfile):
    """
    Write the CDMS matches to a CSV file. Include a header of column names
    which are based on the group and variable names from the netCDF file.
    
    Parameters
    ----------
    matches : list
        The list of dictionaries containing the CDMS matches as returned from
        assemble_matches.      
    csvfile : str
        The name of the CSV output file.
    """
    # Create a header for the CSV. Column names are GROUP_VARIABLE or
    # GROUP_GROUPID.
    header = []
    for key, value in matches[0].items():
        for otherkey in value.keys():
            header.append(key + "_" + otherkey)
    
    try:
        # Write the CSV file
        with open(csvfile, 'w') as output_file:
            csv_writer = csv.writer(output_file)
            csv_writer.writerow(header)
            for match in matches:
                row = []
                for group, data in match.items():
                    for value in data.values():
                        row.append(value)
                csv_writer.writerow(row)
    except (OSError, IOError) as err:
        LOGGER.exception("Error writing CSV file " + csvfile)
        raise err