Write data to csv file
485699
def write_data_csv(fname, frames, preproc):
   """"""
   fdata = open(fname, "w")
   dr = Parallel()(delayed(get_data)(lst,preproc) for lst in frames)
   data,result = zip(*dr)
   for entry in data:
      fdata.write(','.join(entry)+'\r\n')
   print("All finished, %d slices in total" % len(data))
   fdata.close()
   result = np.ravel(result)
   return result
571307
def WriteRow(stream, values):
  ""
  stream.write(','.join([EncodeForCSV(val) for val in values]))
  stream.write('\n')
484695
def write_data(self, data, file_datetime):
        
        with self.__lock:
            assert data is not None
            absolute_file_path = self.__file_path
            #logging.debug("WRITE data file %s for %s", absolute_file_path, key)
            make_directory_if_needed(os.path.dirname(absolute_file_path))
            properties = self.read_properties() if os.path.exists(absolute_file_path) else dict()
            write_zip(absolute_file_path, data, properties)
            # convert to utc time.
            tz_minutes = Utility.local_utcoffset_minutes(file_datetime)
            timestamp = calendar.timegm(file_datetime.timetuple()) - tz_minutes * 60
            os.utime(absolute_file_path, (time.time(), timestamp))
992866
private static byte[] writeCsv(String[] columnHeaders, String[][] rows) throws IOException {
    try (ByteArrayOutputStream csvStream = new ByteArrayOutputStream(); OutputStreamWriter streamWriter = new OutputStreamWriter(csvStream, Charset.forName("UTF-8"))) {
      CSVWriter csvWriter = new CSVWriter(streamWriter, ',');

      csvWriter.writeNext(columnHeaders);
      
      for (String[] row : rows) {
        csvWriter.writeNext(row);
      }

      csvWriter.close();
      
      return csvStream.toByteArray();
    }
  }
586268
def savecsv(self, filename):
        ''''''
        f = open(filename, mode='w')
        headers = ["Seq", "Frame", "Cmd", "P1", "P2", "P3", "P4", "X", "Y", "Z"]
        print(self.csv_line(headers))
        f.write(self.csv_line(headers) + "\n")
        for w in self.wploader.wpoints:
            if getattr(w, 'comment', None):
#                f.write("# %s\n" % w.comment)
                pass
            out_list = [ w.seq,
                         self.pretty_enum_value('MAV_FRAME', w.frame),
                         self.pretty_enum_value('MAV_CMD', w.command),
                         self.pretty_parameter_value(w.param1),
                         self.pretty_parameter_value(w.param2),
                         self.pretty_parameter_value(w.param3),
                         self.pretty_parameter_value(w.param4),
                         self.pretty_parameter_value(w.x),
                         self.pretty_parameter_value(w.y),
                         self.pretty_parameter_value(w.z),
                         ]
            print(self.csv_line(out_list))
            f.write(self.csv_line(out_list) + "\n")
        f.close()
1363439
def to_csv(args):
    
    result_file = args.result_file
    output_file = args.output_file
    delimiter = args.delimiter
    if not os.path.isfile(result_file):
        raise OSError("Results file does not exists")
    headers = ['elapsed', 'epoch', 'turret_name', 'scriptrun_time', 'error']
    headers_row = {}

    set_database(result_file, db, {})

    results = Result.select()

    for item in results:
        result_item = item.to_dict()
        for k in result_item['custom_timers'].keys():
            if k not in headers:
                headers.append(k)
                headers_row[k] = k

    with open(output_file, "w+") as f:
        writer = csv.DictWriter(f, fieldnames=headers, delimiter=delimiter)
        headers_row.update({
            'elapsed': 'elapsed time',
            'epoch': 'epoch (in seconds)',
            'turret_name': 'turret name',
            'scriptrun_time': 'transaction time',
            'error': 'error'
        })
        writer.writerow(headers_row)
        for result_item in results:
            line = result_item.to_dict()
            for key, value in line['custom_timers'].items():
                line[key] = value
            del line['custom_timers']
            writer.writerow(line)
1145884
def write_csvs(dirname: PathLike, adata: AnnData, skip_data: bool = True, sep: str = ','):
    
    dirname = Path(dirname)
    if dirname.suffix == '.csv':
        dirname = dirname.with_suffix('')
    logger.info("writing '.csv' files to %s", dirname)
    if not dirname.is_dir():
        dirname.mkdir(parents=True, exist_ok=True)
    dir_uns = dirname / 'uns'
    if not dir_uns.is_dir():
        dir_uns.mkdir(parents=True, exist_ok=True)
    d = dict(
        obs=adata._obs,
        var=adata._var,
        obsm=adata._obsm.to_df(),
        varm=adata._varm.to_df(),
    )
    if not skip_data:
        d['X'] = pd.DataFrame(
            adata._X.toarray() if issparse(adata._X) else adata._X)
    d_write = {**d, **adata._uns}
    not_yet_raised_sparse_warning = True
    for key, value in d_write.items():
        if issparse(value):
            if not_yet_raised_sparse_warning:
                warnings.warn('Omitting to write sparse annotation.')
                not_yet_raised_sparse_warning = False
            continue
        filename = dirname
        if key not in {'X', 'var', 'obs', 'obsm', 'varm'}:
            filename = dir_uns
        filename /= '{}.csv'.format(key)
        df = value
        if not isinstance(value, pd.DataFrame):
            value = np.array(value)
            if np.ndim(value) == 0:
                value = value[None]
            try:
                df = pd.DataFrame(value)
            except Exception as e:
                warnings.warn('Omitting to write {!r}.'.format(key), type(e))
                continue
        df.to_csv(
            filename, sep=sep,
            header=key in {'obs', 'var', 'obsm', 'varm'},
            index=key in {'obs', 'var'},
        )
850047
def write (self, data):
        """"""
        assert isinstance(data, unicode)
        if self.closed:
            raise IOError("Write on closed I/O object")
        if data:
            self.buf.append(data)
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
1152262
def export_to_csv(self, entities: List[str], filename="sensors.csv"):
        
        if not set(entities).issubset(set(self._sensors_num_df.columns.tolist())):
            print("Invalid entities entered, aborting export_to_csv")
            return
        try:
            self._sensors_num_df[entities].to_csv(path_or_buf=filename)
            print(f"Successfully exported entered entities to {filename}")
        except Exception as exc:
            print(exc)
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()
143244
def output_csv(filehandle: TextIO, values: Iterable[str]) -> None:
    
    line = ",".join(values)
    filehandle.write(line + "\n")
1118291
def write_csv(graph, prefix):
    
    node_headers = list(set([a for n, attrs in graph.nodes(data=True)
                             for a in attrs.keys()]))
    edge_headers = list(set([a for s, t, attrs in graph.edges(data=True)
                             for a in attrs.keys()]))

    value = lambda attrs, h: _recast_value(attrs[h]) if h in attrs else ''
    with open(prefix + '_nodes.csv', 'w') as f:
        writer = csv.writer(f)
        writer.writerow(['node'] + node_headers)
        for n, attrs in graph.nodes(data=True):
            values = map(value, repeat(attrs, len(node_headers)), node_headers)
            writer.writerow([_recast_value(n)] + list(values))

    with open(prefix + '_edges.csv', 'w') as f:
        writer = csv.writer(f)
        writer.writerow(['source', 'target'] + edge_headers)
        for s, t, attrs in graph.edges(data=True):
            values = map(value, repeat(attrs, len(edge_headers)), edge_headers)
            writer.writerow([_recast_value(s), _recast_value(t)] + list(values))
323174
def store_contents(self):
        

        string_buffer = os.linesep.join(
            map(
                lambda x: ",".join(x),
                map(
                    lambda x: map(
                        str,
                        x.values()
                    ),
                    self.rows
                )
            )
        )

        with open(self.name + ".csv", "w") as f:
            f.write(string_buffer)
417690
def write_csv(fileobj, rows, encoding=ENCODING, dialect=DIALECT):
    """"""
    csvwriter = csv.writer(fileobj, dialect=dialect)
    csv_writerows(csvwriter, rows, encoding)
1101515
function outputFile(configId, outputdata){
  var fname= configId+ '_accounts.csv';
  console.log("Outputing file... "+fname);
  var input= {
    data: outputdata,
    fields: ['id','name','status','subscriptionStarts','subscriptionExpires']
  };
  json2csv(input, function(err, csv) {
    if (err) {
      console.log('ERROR!');
      console.log(err);
    } else {
      fs.writeFileSync(fname,csv);
    }
  });
}
635353
def write(fname, data):
		
		try:
			with open(fname, 'w') as f:
				json.dump(data, f)

		except IOError:
			raise Exception('Could not open {0!s} for writing'.format((fname)))