Write CSV file. Sorts the sections before calling the superclass write_csv
170516
def write_csv(self, path=None):
        """"""

        # Sort the Sections

        self.sort_sections(['Root', 'Contacts', 'Documentation', 'References', 'Resources', 'Citations', 'Schema'])

        # Sort Terms in the root section

        # Re-wrap the description and abstract
        if self.description:
            self.description = self.description

        if self.abstract:
            self.description = self.abstract

        t = self['Root'].get_or_new_term('Root.Modified')
        t.value = datetime_now()

        self.sort_by_term()

        return super().write_csv(str(path))
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)
38913
def write(self, f):
        
        if isinstance(f, str):
            f = io.open(f, 'w', encoding='utf-8')

        if not hasattr(f, 'read'):
            raise AttributeError("Wrong type of file: {0}".format(type(f)))

        NS_LOGGER.info('Write to `{0}`'.format(f.name))
        for section in self.sections.keys():
            f.write('[{0}]\n'.format(section))
            for k, v in self[section].items():
                f.write('{0:15}= {1}\n'.format(k, v))
            f.write('\n')
        f.close()
673931
def _write_csv(f, table_):
    
    fieldnames = table_[0].keys()
    set_fieldname = set(table_[0].keys())
    # go through all the fields and find all the field names
    for row in table_:
        set_fieldname.update(set(row.keys()))

    # append the additonal fields sorted onto the end
    additional_fields = sorted(set_fieldname - set(table_[0].keys()))
    fieldnames += additional_fields

    writer = unicodecsv.DictWriter(f, fieldnames, encoding='utf-8')
    writer.writeheader()

    # Change lists into comma-separated strings.
    for dict_ in table_:
        for key, value in dict_.items():
            if type(value) in (list, tuple):
                dict_[key] = ', '.join([unicode(v) for v in value])

    writer.writerows(table_)
1125817
function (file, writeOptions) {
  writeOptions = writeOptions || {};
  file = formattingPreflight(file, 'csv');
  try {
    return csvFormat(file, writeOptions.columns);
  } catch (err) {
    parseError('csv');
  }
}
1235202
public static void writeConfigFile(String fileName, boolean sortClasses) throws SQLException, IOException {
		List<Class<?>> classList = new ArrayList<Class<?>>();
		findAnnotatedClasses(classList, new File("."), 0);
		writeConfigFile(fileName, classList.toArray(new Class[classList.size()]), sortClasses);
	}
871767
def bucketCSVs(csvFile, bucketIdx=2):
  """"""
  try:
    with open(csvFile, "rU") as f:
      reader = csv.reader(f)
      headers = next(reader, None)
      dataDict = OrderedDict()
      for lineNumber, line in enumerate(reader):
        if line[bucketIdx] in dataDict:
          dataDict[line[bucketIdx]].append(line)
        else:
          # new bucket
          dataDict[line[bucketIdx]] = [line]
  except IOError as e:
    print e

  filePaths = []
  for i, (_, lines) in enumerate(dataDict.iteritems()):
    bucketFile = csvFile.replace(".", "_"+str(i)+".")
    writeCSV(lines, headers, bucketFile)
    filePaths.append(bucketFile)

  return filePaths
596510
def joinCSVs(csvFilePaths, column, ouputFileName, separator = ',') :
	
	
	res = ''
	legend = []
	csvs = []
	
	for f in csvFilePaths :
		c = CSVFile()
		c.parse(f)
		csvs.append(c)
		legend.append(separator.join(c.legend.keys()))
	legend = separator.join(legend)
	
	lines = []
	for i in range(len(csvs[0])) :
		val = csvs[0].get(i, column)
		line = separator.join(csvs[0][i])
		for c in csvs[1:] :
			for j in range(len(c)) :
				if val == c.get(j, column) :
					line += separator + separator.join(c[j])
					
		lines.append( line )
	
	res = legend + '\n' + '\n'.join(lines)
	
	f = open(ouputFileName, 'w')
	f.write(res)
	f.flush()
	f.close()
	
	return res
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))
1007727
def write_config_file(self, f, comments):
        
        if len(self.elements) < 1:
            return
        super(_Section, self).write_config_file(f, comments)

        for e in self.elements.values():
            e.write_config_file(f, comments)
        f.write("\n")
598878
def csv_writer(csvfile):
        
        if sys.version_info >= (3,):
            writer = csv.writer(csvfile, delimiter=',', lineterminator='\n')
        else:
            writer = csv.writer(csvfile, delimiter=b',', lineterminator='\n')

        return writer
970402
def writeFromDict(dataDict, headers, csvFile):
  
  with open(csvFile, "wb") as f:
    writer = csv.writer(f, delimiter=",")
    writer.writerow(headers)
    for row in sorted(dataDict.keys()):
      writer.writerow(dataDict[row])
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
90181
def write(self):
        
        writer = csv.writer(self.file)

        for f, b in zip(self.gb.result["forward"], self.gb.result["backward"]):
            f = f._asdict()
            b = b._asdict()
            if not self.check_same(f, b):
                raise AssertionError()

            args_info = ", ".join(["{}: {}".format(k, v)
                                   for k, v in f["args_info"]])

            out = [f["parameter_scope"], f["function_name"], f["inputs_shape"], args_info,
                   f["mean_time"], b["mean_time"], f["n_run"], b["n_run"]]

            writer.writerow(out)

        writer.writerow([])
        writer.writerow(["forward all", self.gb.result["forward_all"]])
        writer.writerow(
            ["forward_all_n_run", self.gb.result["n_run_forward_all"]])

        writer.writerow([])
        writer.writerow(["backward all", self.gb.result["backward_all"]])
        writer.writerow(
            ["backward_all_n_run", self.gb.result["n_run_backward_all"]])

        if set(self.gb.result.keys()) >= {"training", "n_run_training"}:
            writer.writerow([])
            writer.writerow(
                ["training(forward + backward + update)", self.gb.result["training"]])
            writer.writerow(
                ["training_n_run", self.gb.result["n_run_training"]])
1284668
def write_csv_files(args, infilenames, outfilename):
    
    def csv_convert(line):
        """Strip punctuation and insert commas"""
        clean_line = []
        for word in line.split(' '):
            clean_line.append(word.strip(string.punctuation))
        return ', '.join(clean_line)

    if not outfilename.endswith('.csv'):
        outfilename = outfilename + '.csv'
    outfilename = overwrite_file_check(args, outfilename)

    all_text = []  # Text must be aggregated if writing to a single output file
    for i, infilename in enumerate(infilenames):
        parsed_text = get_parsed_text(args, infilename)
        if parsed_text:
            if args['multiple']:
                if not args['quiet']:
                    print('Attempting to write to {0}.'.format(outfilename))

                csv_text = [csv_convert(x) for x in parsed_text]
                print(csv_text)
                write_file(csv_text, outfilename)
            elif args['single']:
                all_text += parsed_text
                # Newline added between multiple files being aggregated
                if len(infilenames) > 1 and i < len(infilenames) - 1:
                    all_text.append('\n')

    # Write all text to a single output file
    if args['single'] and all_text:
        if not args['quiet']:
            print('Attempting to write {0} page(s) to {1}.'
                  .format(len(infilenames), outfilename))

        csv_text = [csv_convert(x) for x in all_text]
        print(csv_text)
        write_file(csv_text, outfilename)
896169
def _organize_by_position(orig_file, cmp_file, chunk_size):
    
    with open(orig_file) as in_handle:
        reader1 = csv.reader(in_handle)
        positions = len(next(reader1)) - 1
    for positions in _chunks(range(positions), chunk_size):
        with open(orig_file) as orig_handle:
            with open(cmp_file) as cmp_handle:
                orig_reader = csv.reader(orig_handle)
                cmp_reader = csv.reader(cmp_handle)
                for item in _counts_at_position(positions,
                        orig_reader, cmp_reader):
                    yield item
196609
def write_csv_to_file(d):
    
    logger_csvs.info("enter write_csv_to_file")

    try:
        for filename, data in d.items():
            try:
                l_columns = _reorder_csv(data, filename)
                rows = zip(*l_columns)
                with open(filename, 'w+') as f:
                    w = csv.writer(f)
                    for row in rows:
                        row2 = decimal_precision(row)
                        w.writerow(row2)
            except TypeError as e:
                print("Error: Unable to write values to CSV file, {}:\n"
                      "(1) The data table may have 2 or more identical variables. Please correct the LiPD file manually\n"
                      "(2) There may have been an error trying to prep the values for file write. The 'number' field in the data columns may be a 'string' instead of an 'integer' data type".format(filename))
                print(e)
            except Exception as e:
                print("Error: CSV file not written, {}, {}:\n"
                      "The data table may have 2 or more identical variables. Please correct the LiPD file manually".format(filename, e))
    except AttributeError as e:
        logger_csvs.error("write_csv_to_file: Unable to write CSV File: {}".format(e, exc_info=True))
    logger_csvs.info("exit write_csv_to_file")
    return