Stores the processing results in a file. CSV (comma separated values) is
a simple format that makes sense for such tasks. It can be imported
easily into spreadsheet tools to generate diagrams from the data.
6782
public void storeResults() {
		System.out.println("Processed " + countItems + " items and "
				+ countProperties + " properties in total.");
		System.out.println("Storing data ...");

		try (PrintStream out = new PrintStream(new FileOutputStream(
				"tutorial-results.csv"))) {
			// Two simple entries for demonstration purposes.
			// Use your own code when you have more interesting data.
			out.println("count of items," + countItems);
			out.println("count of properties," + countProperties);
		} catch (IOException e) {
			System.out.println("Oops, I could not write the file: "
					+ e.toString());
		}

		System.out.println("... data stored.");

	}
1033939
def _get_results(csv_reader, fieldnames):
    
    fieldnames_count = len(fieldnames)
    results = []
    for row in csv_reader:
        for col in row:
            if col:
                break
        else:
            # empty row, skip it
            continue
        record = OrderedDict(list(zip(fieldnames, row)))
        # skip rows that were already exported
        if record.get("exported") == "yes":
            continue
        row_len = len(row)
        if fieldnames_count > row_len:
            for key in fieldnames[row_len:]:
                record[key] = None
        results.append(record)

    return results
1151478
def save_csv(self, filename, write_header_separately=True):
        
        txt = ''
        #print("SAVING arr = ", self.arr)
        
        with open(filename, "w") as f:
            if write_header_separately:
                f.write(','.join([c for c in self.header]) + '\n')
            for row in self.arr:
                #print('save_csv: saving row = ', row)
                txt = ','.join([self.force_to_string(col) for col in row])
                #print(txt)
                f.write(txt + '\n')
            f.write('\n')
851137
def importcsv(self):
        '''  '''
        csv_path = os.path.join(os.path.dirname(__file__), self.stock_no_files)
        with open(csv_path) as csv_file:
            csv_data = csv.reader(csv_file)
            result = {}
            for i in csv_data:
                try:
                    result[i[0]] = str(i[1]).decode('utf-8')
                except ValueError:
                    if i[0] == 'UPDATE':
                        self.last_update = str(i[1]).decode('utf-8')
                    else:
                        pass
        return result
537985
public final String csv() {
        StringBuilder sb = new StringBuilder();
        String header =
                "#RunID, ClientID, MsgCount, MsgBytes, MsgsPerSec, BytesPerSec, DurationSecs";

        sb.append(String.format("%s stats: %s\n", name, this));
        sb.append(header); sb.append("\n");
        sb.append(csvLines(subs,"S"));
        sb.append(csvLines(pubs,"P"));
        return sb.toString();
    }
324110
@Cmd
	public void processCsvFile(final String csvFile, final String delimiter, final char quoteChar, final Charset charset,
			final Closure<Void> closure) {
		File f = new File(csvFile);
		try {
			config.extractFromArchive(f, true);
			checkState(f.exists(), "CSV file not found: " + f);
			Reader reader = Files.newReader(f, charset == null ? defaultCharset : charset);
			csvDataProcessor.processFile(reader, delimiter, quoteChar, closure);
		} catch (IOException ex) {
			throw new IllegalStateException("Error reading CSV file: " + f, ex);
		}
	}
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()
776291
def csv
      @csv ||= CSV.generate do |csv|
        reports.each(&:report).each do |report|
          # If there are no dimensions, but totals, we need to put an extra
          # column at the start for the word "Total".
          # I don't see how totals will be different than the metrics if you
          # don't specify dimensions, but whatever.
          totals_column = report.totals? && !report.dimensions? ? [nil] : []
          csv << totals_column + report.headers
          report.rows.each { |row| csv << totals_column + row.to_a }
          next unless report.totals? # Rubocop did this. Not sure I like it.
          csv << ["Totals"] + if !report.dimensions?
                                report.totals
                              else
                                report.totals[1..-1]
                              end
        end
      end
    end
254141
def my_import(file):
    
    # , help="The path to the CSV file to import. The first row must contain column names."
    lines = None
    with open(file) as csv_file:
        lines = csv_file.readlines()

    # Header, the first line.
    header = lines[0]
    lines.remove(header)
    header = header.rstrip()

    # Parse records from a csv row.
    counter = 0
    app = AppAggregate()
    app.open_session()
    for line in lines:
        # Create insert statements
        line = line.rstrip()
        command = f"insert into AssetClass ({header}) values ({line});"
        # insert records
        app.session.execute(command)
        try:
            app.save()
        except:
            print(f"error: ", sys.exc_info()[0])
            app.session.close()
        counter += 1
    print(f"Data imported. {counter} rows created.")
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)
721172
def _convert_html_to_csv(
            self):
        
        self.log.info('starting the ``_convert_html_to_csv`` method')

        import codecs
        allData = ""
        regex1 = re.compile(
            r'.*<PRE><strong>   (.*?)</strong>(.*?)</PRE></TABLE>.*', re.I | re.S)
        regex2 = re.compile(r'\|(\w)\|', re.I | re.S)
        for thisFile in self.nedResults:
            pathToReadFile = thisFile
            try:
                self.log.debug("attempting to open the file %s" %
                               (pathToReadFile,))
                readFile = codecs.open(
                    pathToReadFile, encoding='utf-8', mode='r')
                thisData = readFile.read()
                readFile.close()
            except IOError, e:
                message = 'could not open the file %s' % (pathToReadFile,)
                self.log.critical(message)
                raise IOError(message)
            except:
                if pathToReadFile == None:
                    message = 'we have no file to open'
                    self.log.error(message)
                    continue
            readFile.close()

            self.log.debug("regex 1 - sub")
            thisData = regex1.sub("\g<1>\g<2>", thisData)
            self.log.debug("regex 2 - sub")
            thisData = regex2.sub("abs(\g<1>)", thisData)
            self.log.debug("replace text")
            thisData = thisData.replace("|b|", "abs(b)")

            writeFile = codecs.open(pathToReadFile, encoding='utf-8', mode='w')
            writeFile.write(thisData)
            writeFile.close()

        self.log.info('completed the ``_convert_html_to_csv`` method')
        return None
170228
function csv(array)
	{
		if (!(array instanceof Array) || array.length === 0)
			return '';

		array = array.slice(0);

		var i = array.length;
		while (i--)
			array[i] = '"' + (''+array[i]).replace(/(\\|")/g, '\\$1') + '"';

		return array.join(', ');
	}
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))
938632
def to_csv(options={})
      CSV.generate(options) do |csv|
        csv << scope.attributes
        csv << attributes_hash.values
      end
    end
325168
def to_csv(path = nil)
      out_io = path ? File.open(path, 'w') : $stdout
      csv = CSV.new(out_io, force_quotes: true)
      csv << column_names
      each { |record| csv << record.to_a }
    end
35119
def csv(self, fh):
        
        self._stats.to_csv(fh, encoding='utf-8', index=False)
        return fh
925273
def to_csv(format = :long)
      output = ''
      
      columns = []
      # only output
      case format
      when :long
        columns.concat([@id, @updated, @title])
      end
      
      # output all dimensions
      columns.concat(@dimensions.map {|d| d.value})
      
      # output all metrics
      columns.concat(@metrics.map {|m| m.value})

      output = CSV.generate_line(columns)      
      return output
    end