Write rows data to a CSV file (with or without fieldnames)
979197
def write_csv(path, rows, dialect='excel', fieldnames=None, quoting=csv.QUOTE_ALL, extrasaction='ignore', *args, **kwargs):
        '''  '''
        if not quoting:
            quoting = csv.QUOTE_MINIMAL
        if 'lineterminator' not in kwargs:
            kwargs['lineterminator'] = '\n'  # use \n to fix double-line in Windows
        with open(path, mode='wt', newline='') as csvfile:
            if fieldnames:
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames, dialect=dialect, quoting=quoting, extrasaction=extrasaction, *args, **kwargs)
                writer.writeheader()
                for row in rows:
                    writer.writerow(row)
            else:
                writer = csv.writer(csvfile, dialect=dialect, quoting=quoting, *args, **kwargs)
                for row in rows:
                    writer.writerow(row)
290229
def write_csv_line(mol, csv_writer, options):
    

    # set variables
    status_field = options.status_field

    # elements for writing will be stored in the line list
    line = []

    # ID
    id = mol.GetProp('id')
    if id is not None:
        line.append(id)
    else:
        line.append('n/a')

    # status
    line.append(mol.GetProp(status_field))

    # query labels
    queryList = mol.properties.keys()
    for queryLabel in queryList:
        line.append(mol.properties[queryLabel])

    # write line
    csv_writer.writerow(line)
420776
def _tabulate(rows, headers, spacing=5):
    """"""
    if len(rows) == 0:
        return "None\n"
    assert len(rows[0]) == len(headers)
    count = len(rows[0])
    widths = [0 for _ in range(count)]
    rows = [headers] + rows

    for row in rows:
        for index, field in enumerate(row):
            if len(str(field)) > widths[index]:
                widths[index] = len(str(field))

    output = ""
    for row in rows:
        for index, field in enumerate(row):
            field = str(field)
            output += field + (widths[index] - len(field) + spacing) * " "
        output += "\n"
    return output
509404
def export_to_csv(
    table,
    filename_or_fobj=None,
    encoding="utf-8",
    dialect=unicodecsv.excel,
    batch_size=100,
    callback=None,
    *args,
    **kwargs
):
    
    # TODO: will work only if table.fields is OrderedDict
    # TODO: should use fobj? What about creating a method like json.dumps?

    return_data, should_close = False, None
    if filename_or_fobj is None:
        filename_or_fobj = BytesIO()
        return_data = should_close = True

    source = Source.from_file(
        filename_or_fobj,
        plugin_name="csv",
        mode="wb",
        encoding=encoding,
        should_close=should_close,
    )

    # TODO: may use `io.BufferedWriter` instead of `ipartition` so user can
    # choose the real size (in Bytes) when to flush to the file system, instead
    # number of rows
    writer = unicodecsv.writer(source.fobj, encoding=encoding, dialect=dialect)

    if callback is None:
        for batch in ipartition(serialize(table, *args, **kwargs), batch_size):
            writer.writerows(batch)

    else:
        serialized = serialize(table, *args, **kwargs)
        writer.writerow(next(serialized))  # First, write the header
        total = 0
        for batch in ipartition(serialized, batch_size):
            writer.writerows(batch)
            total += len(batch)
            callback(total)

    if return_data:
        source.fobj.seek(0)
        result = source.fobj.read()
    else:
        source.fobj.flush()
        result = source.fobj

    if source.should_close:
        source.fobj.close()

    return result
1132714
def _make_record(self,row):
        """"""
        res = dict(zip(['__id__']+[f for f in self.fields],row))
        for field_name in self.conv_func:
            res[field_name] = self.conv_func[field_name](res[field_name])
        return res
588819
def save_csvf(data: list, fieldnames: Sequence[str], fpath: str, encoding: str, with_header: bool = False,
              crlf: bool = False, tsv: bool = False) -> str:
    
    with codecs.open(fpath, mode='w', encoding=encoding) as f:
        f.write(dump_csv(data, fieldnames, with_header=with_header, crlf=crlf, tsv=tsv))
        return fpath
504943
function toCSVString(data, params) {
    if (data.length === 0) {
      return '';
    }
    params = params || {};

    var header = params.headers || [],
        plainObject = isPlainObject(data[0]),
        keys = plainObject && (params.order || keysIndex(data)),
        oData,
        i;

    // Defaults
    var escape = params.escape || '"',
        delimiter = params.delimiter || ',';

    // Dealing with headers polymorphism
    if (!header.length)
      if (plainObject && params.headers !== false)
        header = keys;

    // Should we append headers
    oData = (header.length ? [header] : []).concat(
      plainObject ?
        data.map(function(e) { return objectToArray(e, keys); }) :
        data
    );

    // Converting to string
    return oData.map(function(row) {
      return row.map(function(item) {

        // Wrapping escaping characters
        var i = ('' + (typeof item === 'undefined' ? '' : item)).replace(
          new RegExp(rescape(escape), 'g'),
          escape + escape
        );

        // Escaping if needed
        return ~i.indexOf(delimiter) || ~i.indexOf(escape) || ~i.indexOf('\n') ?
          escape + i + escape :
          i;
      }).join(delimiter);
    }).join('\n');
  }
869544
def _write_data_csv(csv_data):
    
    logger_excel.info("enter write_data_csv")
    # Loop for each file and data that is stored
    for file in csv_data:
        for filename, data in file.items():
            # Make sure we're working with the right data types before trying to open and write a file
            if isinstance(filename, str) and isinstance(data, list):
                try:
                    with open(filename, 'w+') as f:
                        w = csv.writer(f)
                        for line in data:
                            w.writerow(line)
                except Exception:
                    logger_excel.debug("write_data_csv: Unable to open/write file: {}".format(filename))

    logger_excel.info("exit write_data_csv")
    return
1338234
def WriteRow(self, values):
    
    precondition.AssertDictType(values, text, text)

    row = []
    for column in self._columns:
      try:
        value = values[column]
      except KeyError:
        raise ValueError("Row does not contain required column `%s`" % column)

      row.append(value)

    self._writer.WriteRow(row)
719526
def write(self, bucket, rows, keyed=False, as_generator=False, update_keys=None):
        

        # Check update keys
        if update_keys is not None and len(update_keys) == 0:
            message = 'Argument "update_keys" cannot be an empty list'
            raise tableschema.exceptions.StorageError(message)

        # Get table and description
        table = self.__get_table(bucket)
        schema = tableschema.Schema(self.describe(bucket))
        fallbacks = self.__fallbacks.get(bucket, [])

        # Write rows to table
        convert_row = partial(self.__mapper.convert_row, schema=schema, fallbacks=fallbacks)
        writer = Writer(table, schema, update_keys, self.__autoincrement, convert_row)
        with self.__connection.begin():
            gen = writer.write(rows, keyed=keyed)
            if as_generator:
                return gen
            collections.deque(gen, maxlen=0)
926894
def write_csv(data, file_name, encoding='utf-8'):
    '''
    
    '''
    name_extension = len(data) > 1
    root, ext = os.path.splitext(file_name)

    for i, sheet in enumerate(data):
        fname = file_name if not name_extension else root+"_"+str(i)+ext
        with open(fname, 'wb') as date_file:
            csv_file = csv.writer(date_file, encoding=encoding)
            for line in sheet:
                csv_file.writerow(line)
1265543
def writeToCSV(self, output_path=None):
        '''
        '''
        header = ['Name', 'First Byte', 'Last Byte', 'Bit Mask', 'Endian',
                  'Type', 'Description', 'Values']

        if output_path is None:
            output_path = ait.config._directory

        for pkt_name in self.tlmdict:
            filename = os.path.join(output_path, pkt_name + '.csv')

            with open(filename, 'wb') as output:
                csvwriter = csv.writer(output, quoting=csv.QUOTE_ALL)
                csvwriter.writerow(header)

                for fld in self.tlmdict[pkt_name].fields:
                    # Pre-process some fields

                    # Description
                    desc = fld.desc.replace('\n', ' ') if fld.desc is not None else ""

                    # Mask
                    mask = hex(fld.mask) if fld.mask is not None else ""

                    # Enumerations
                    enums = '\n'.join("%s: %s" % (k, fld.enum[k])
                            for k in fld.enum) if fld.enum is not None else ""

                    # Set row
                    row = [fld.name, fld.slice().start, fld.slice().stop,
                           mask, fld.type.endian, fld.type.name, desc, enums]

                    csvwriter.writerow(row)
663644
def populate_csv_headers(rows,
                         partial_headers,
                         column_headers_count=1):
    

    result = [''] * (len(rows) - column_headers_count)

    for i_index in range(0, len(partial_headers)):
        for k_index in range(0, len(partial_headers[i_index])):

            # missing field find for a value in upper rows
            if not partial_headers[i_index][k_index] and i_index - 1 >= 0:

                # TODO: It's necesary a for or only taking the
                # inmediate latest row works well??
                for t_index in range(i_index - 1, -1, -1):
                    # TODO: could suposse that allways a value exists
                    partial_value = partial_headers[t_index][k_index]
                    if partial_value:
                        partial_headers[i_index][k_index] = partial_value
                        break

        result[i_index] = " ".join(map(str, partial_headers[i_index]))

    return result
125500
def xlsw_write_row(ws, row_idx, row, fmt=None):
    
    for col_idx in range(len(row)):
        ws.write(row_idx, col_idx, row[col_idx], fmt)
    row_idx += 1
    return row_idx
181832
def dump_csv(data: List[dict], fieldnames: Sequence[str], with_header: bool = False, crlf: bool = False,
             tsv: bool = False) -> str:
    

    def force_str(v):
        # XXX: Double quotation behaves strangely... so replace (why?)
        return dump_json(v).replace('"', "'") if isinstance(v, (dict, list)) else v

    with io.StringIO() as sio:
        dialect = get_dialect_name(crlf, tsv)
        writer = csv.DictWriter(sio, fieldnames=fieldnames, dialect=dialect, extrasaction='ignore')
        if with_header:
            writer.writeheader()
        for x in data:
            writer.writerow({k: force_str(v) for k, v in x.items()})
        sio.seek(0)
        return sio.read()
217398
def write_data_chunk(self, rows, indexes, mask, values):
        

        # 0 len
        for v in values:
            if not np.prod(v.shape):
                return

        try:
            nrows = indexes[0].shape[0]
            if nrows != len(rows):
                rows = np.empty(nrows, dtype=self.dtype)
            names = self.dtype.names
            nindexes = len(indexes)

            # indexes
            for i, idx in enumerate(indexes):
                rows[names[i]] = idx

            # values
            for i, v in enumerate(values):
                rows[names[i + nindexes]] = v

            # mask
            if mask is not None:
                m = ~mask.ravel().astype(bool, copy=False)
                if not m.all():
                    rows = rows[m]

        except Exception as detail:
            raise Exception(
                "cannot create row-data -> {detail}".format(detail=detail))

        try:
            if len(rows):
                self.table.append(rows)
                self.table.flush()
        except Exception as detail:
            raise TypeError(
                "tables cannot write this data -> {detail}".format(
                    detail=detail))
100106
def writerow(self, row):
    """"""
    encoded_row = []
    for s in row:
      if isinstance(s, unicode):
        encoded_row.append(s.encode("utf-8"))
      else:
        encoded_row.append(s)
    try:
      self.writer.writerow(encoded_row)
    except Exception as e:
      print('error writing %s as %s' % (row, encoded_row))
      raise e