CSV outputted with Headers as first set of results.
512759
def _init(self):
        """"""
        # Note that we assume params.json was already created by JsonLogger
        progress_file = os.path.join(self.logdir, "progress.csv")
        self._continuing = os.path.exists(progress_file)
        self._file = open(progress_file, "a")
        self._csv_out = None
1373923
def parse_results_header(cls, header):
        
        header = IORMetricsExtractor.RE_MULTIPLE_SPACES.sub(' ', header)
        header = header.split(' ')
        return header
901132
def make_csv(data):
    
    # Convert sub-dicts to news cols
    for entry in data:
        rval = entry
        if isinstance(data, dict):
            rval = data[entry]
        todel = []
        toadd = {}
        for key, val in rval.items():
            if isinstance(val, dict):
                for key2, val2 in val.items():
                    toadd[str(key) + "[" + str(key2) + "]"] = val2
                todel.append(key)
        for k in todel:
            del rval[k]
        for k, v in toadd.items():
            rval[k] = v

    # Convert everything to CSV
    columns = set()
    output = [[]]
    if isinstance(data, dict):
        output[0].append("id")
        for entry in data:
            for col in data[entry]:
                columns.add(col)
    else:
        for entry in data:
            for col in entry:
                columns.add(col)

    columns = sorted(columns)

    for col in columns:
        output[0].append(col)

    if isinstance(data, dict):
        for entry in data:
            new_output = [str(entry)]
            for col in columns:
                new_output.append(str(data[entry][col]) if col in data[entry] else "")
            output.append(new_output)
    else:
        for entry in data:
            new_output = []
            for col in columns:
                new_output.append(str(entry[col]) if col in entry else "")
            output.append(new_output)

    csv_string = io.StringIO()
    csv_writer = UnicodeWriter(csv_string)
    for row in output:
        csv_writer.writerow(row)
    csv_string.seek(0)
    web.header('Content-Type', 'text/csv; charset=utf-8')
    web.header('Content-disposition', 'attachment; filename=export.csv')
    return csv_string.read()
856348
def write(self):
        
        csv_file = os.path.join(self.outdir, 'search_results.csv')
        txt_file = os.path.join(self.outdir, 'unresolved.txt')
        headers = self.key_terms
        unresolved = []
        with open(csv_file, 'w') as file:
            writer = csv.writer(file)
            writer.writerow(headers)
            for key in list(self._store.keys()):
                results = self._store[key]
                if len(results) == 0:
                    unresolved.append(key)
                else:
                    row = [key]
                    for key_term in headers[1:]:
                        element = results[0][key_term]
                        # GNR returns UTF-8, csv requires ascii
                        #
                        # *** Note ***
                        # According to all docs for csv versions >= 2.6, csv
                        # can handle either UTF-8 or ascii, just not Unicode.
                        # In py3, the following two lines result in csv printing
                        # the element with a bitstring. If GNR is actually
                        # returning UTF-8, it seems easiest to just drop these

                        # if 'encode' in dir(element):
                        #     element = element.encode('ascii')
                        row.append(element)
                    writer.writerow(row)
        if len(unresolved) > 0:
            with open(txt_file, 'w') as file:
                for name in unresolved:
                    file.write("{0}\n".format(name))
61687
def extract_headers(headers):
    """"""
    sorted_headers = {}
    matches = re.findall(r'(.*):\s(.*)', headers)
    for match in matches:
        header = match[0]
        value = match[1]
        try:
            if value[-1] == ',':
                value = value[:-1]
            sorted_headers[header] = value
        except IndexError:
            pass
    return sorted_headers
1160084
def as_csv(self):
        """"""

        from io import StringIO

        s = StringIO()
        w = csv.writer(s)
        for row in self.rows:
            w.writerow(row)

        return s.getvalue()
292774
function csvToMapping(csvString) {
  const lines = csvString.split(/\n|\r|\r\n/);
  const header = lines.shift().split(',');
  const key = header.shift();
  const now = new Date();
  const headerIdx = [];
  const fields = [];
  header.forEach((h, i) => {
    if (h === '') return;
    headerIdx.push(i);
    fields.push({key: h, format: 'text'});
  });
  const mapping = {
    created: now.toString(),
    fields: fields,
    key: key,
    mapping: {}
  };
  lines.forEach(line => {
    const values = line.split(',');
    const k = values.shift();
    mapping.mapping[k] = Array(headerIdx.length);
    headerIdx.forEach(i => {
      mapping.mapping[k][i] = values[i];
    });
  });
  return mapping;
}
272779
def print_csv(headers, data_list, parse_row_fn):
    
    try:
        writer = csv.writer(sys.stdout)
        writer.writerow(headers)
        for data in data_list:
            writer.writerow(parse_row_fn(data))
    except csv.Error as e:
        raise CliException('Error writing CSV: {}'.format(e))
1228427
def csv_header_and_defaults(features, schema, stats, keep_target):
  """"""

  target_name = get_target_name(features)
  if keep_target and not target_name:
    raise ValueError('Cannot find target transform')

  csv_header = []
  record_defaults = []
  for col in schema:
    if not keep_target and col['name'] == target_name:
      continue

    # Note that numerical key columns do not have a stats entry, hence the use
    # of get(col['name'], {})
    csv_header.append(col['name'])
    if col['type'].lower() == INTEGER_SCHEMA:
      dtype = tf.int64
      default = int(stats['column_stats'].get(col['name'], {}).get('mean', 0))
    elif col['type'].lower() == FLOAT_SCHEMA:
      dtype = tf.float32
      default = float(stats['column_stats'].get(col['name'], {}).get('mean', 0.0))
    else:
      dtype = tf.string
      default = ''

    record_defaults.append(tf.constant([default], dtype=dtype))

  return csv_header, record_defaults
345603
def parse_csv_header(line):
    """"""
    units = {}
    names = []
    for var in line.split(','):
        start = var.find('[')
        if start < 0:
            names.append(str(var))
            continue
        else:
            names.append(str(var[:start]))
        end = var.find(']', start)
        unitstr = var[start + 1:end]
        eq = unitstr.find('=')
        if eq >= 0:
            # go past = and ", skip final "
            units[names[-1]] = unitstr[eq + 2:-1]
    return names, units
564842
def _write_csv(self, datasets, filename):
        
        with open('/'.join([self.output, filename]), mode='w', encoding=self.encoding) as write_file:
            writer = csv.writer(write_file, delimiter=',')
            for i, row in enumerate(datasets):
                if i == 0:
                    # header
                    writer.writerow(list(row.keys()))
                writer.writerow(list(row.values()))
1325996
def gen_csv(sc, filename, field_list, source, filters):
    '''
    '''

    # First thing we need to do is initialize the csvfile and build the header
    # for the file.
    datafile = open(filename, 'wb')
    csvfile = csv.writer(datafile)
    header = []
    for field in field_list:
        header.append(fields.fields[field]['name'])
    csvfile.writerow(header)

    debug.write('Generating %s: ' % filename)
    # Next we will run the Security Center query.  because this could be a
    # potentially very large dataset that is returned, we don't want to run out
    # of memory.  To get around this, we will pass the query function the writer
    # function with the appropriate fields so that it is parsed inline.
    fparams = {'fobj': csvfile, 'flist': field_list}
    sc.query('vulndetails', source=source, 
             func=writer, func_params=fparams, **filters)
    debug.write('\n')

    # Lastly we need to close the datafile.
    datafile.close()
1022680
public function loadCSV()
    {
        $parser = new CSVParser($this->file);
        $count = 0;
        foreach ($parser as $row) {
            $this->rows[]= $row;
            $count++;
            if ($count == $this->previewcount) {
                break;
            }
        }
        $firstrow = array_keys($this->rows[0]);

        //hack to include first row as a
        array_unshift($this->rows, array_combine($firstrow, $firstrow));

        if (count($this->rows) > 0) {
            $this->headings = $firstrow;
        }
    }
1100910
def populate_headers(headers):
    
    result = [''] * len(headers[0])
    values = [''] * len(headers)
    for k_index in range(0, len(headers)):
        for i_index in range(0, len(headers[k_index])):
            if headers[k_index][i_index]:
                values[k_index] = normalizer(
                    str(headers[k_index][i_index]))  # pass to str

            if len(exclude_empty_values(result)) > i_index:
                result[i_index] += "-{}".format(values[k_index])
            else:
                result[i_index] += str(values[k_index])

    return result
558414
private static byte[] writeCsv(String[] columnHeaders, List<String[]> rows) throws IOException {
    return writeCsv(columnHeaders, rows.stream().toArray(String[][]::new));
  }
483039
def make_csv(self):
        
        import csv
        try:
            from StringIO import StringIO  # Python 2.7
        except ImportError:
            from io import StringIO

        out = StringIO()
        writer = csv.writer(out, delimiter='|', lineterminator='\n', quoting=csv.QUOTE_MINIMAL)

        if self.function == 'total':
            writer.writerows(self.results)                

        elif self.function == 'top':
            rows = [['Value', self.headers.strip('"')]]
            if self.results[0] is not None:
                for res in self.results:
                    if res is not None:
                        rows.append(tuple([res[0], ','.join(res[1])]))
                writer.writerows(rows)
                
        elif self.function == 'table':
            rows = [[header.strip('"') for header in re.split('\s*,\s*', self.headers)]]

            for res in sorted(self.results, key=lambda x: x[0]):
                row = list(res[:-1])
                lastcol = get_fmt_results(res[-1], limit=10)
                if lastcol[-1][0] == '[' and lastcol[-1][-1] == ']':
                    row.append(u'{0} {1}'.format(u', '.join(lastcol[:-1]), lastcol[-1]))
                else:
                    row.append(u', '.join(lastcol))
                rows.append(row)
            writer.writerows(rows)

        self.csv = out.getvalue()
845662
def csv_to_dicts(file, header=None):
    """"""
    with open(file) as csvfile:
        return [row for row in csv.DictReader(csvfile, fieldnames=header)]