Write data to CSV file with validation.
482044
def _write_int(fname, data, append=True):
    """"""
    # pylint: disable=W0705
    data_ex = pexdoc.exh.addex(ValueError, "There is no data to save to file")
    fos_ex = pexdoc.exh.addex(
        OSError, "File *[fname]* could not be created: *[reason]*"
    )
    data_ex((len(data) == 0) or ((len(data) == 1) and (len(data[0]) == 0)))
    try:
        pmisc.make_dir(fname)
        mode = "w" if append is False else "a"
        if sys.hexversion < 0x03000000:  # pragma: no cover, no branch
            with open(fname, mode) as file_handle:
                csv.writer(file_handle, delimiter=",").writerows(data)
        else:  # pragma: no cover
            with open(fname, mode, newline="") as file_handle:
                csv.writer(file_handle, delimiter=",").writerows(data)
    except (IOError, OSError) as eobj:
        fos_ex(True, _MF("fname", fname, "reason", eobj.strerror))
60144
def write(self, data):
        """"""
        for chunk in chunks(data, 512):
            self.wait_to_write()
            self.comport.write(chunk)
        self.comport.flush()
505734
def save_csv(self, fd):
        
        from pylon.io.excel import CSVWriter
        CSVWriter(self).write(fd)
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()
782171
def write(self, data, method='w'):
        
        # Create list of lists from flat list
        data = data if isinstance(data[0], (list, set, tuple)) else [[d] for d in data]

        # Open file and write rows
        with open(self.file_path, method) as write:
            wr = csv_builtin.writer(write)
            wr.writerows(data)
        return self.file_path
232347
def validate_data(args={})
      args = args.slice(:file_path, :data)
      args = args.compact
      file_path = args[:file_path]
      data = args[:data]

      utf_result = validate_csv(file_path) if file_path
      utf_result = validate_hashes(data) if data
      utf_result
    end
1244698
def write_output(self):
        """"""
        for data in self.output_data.values():
            self.create_output(data.get('key'), data.get('value'), data.get('type'))
146333
def write_output(self, data, args=None, filename=None, label=None):
        """"""
        if args:
            if not args.outlog:
                return 0
        if not filename: filename=args.outlog
        lastpath = ''
        with open(str(filename), 'w') as output_file:
            for entry in data['entries']:
                if args.label:
                    if entry['source_path'] == lastpath:
                        output_file.write(entry['raw_text'] + '\n')
                    elif args.label == 'fname':
                        output_file.write('======== ' + \
                                entry['source_path'].split('/')[-1] + \
                                ' >>>>\n' + entry['raw_text'] + '\n')
                    elif args.label == 'fpath':
                        output_file.write('======== ' + \
                                entry['source_path']  + \
                                ' >>>>\n' + entry['raw_text'] + '\n')
                else: output_file.write(entry['raw_text'] + '\n')
                lastpath = entry['source_path']
1193502
def write(self, iterable):
        """"""

        io_error_text = _("Error writing to file {filepath}.")
        io_error_text = io_error_text.format(filepath=self.path)

        try:

            with open(self.path, "wb") as csvfile:
                csv_writer = csv.writer(csvfile, self.dialect)

                for line in iterable:
                    csv_writer.writerow(
                        list(encode_gen(line, encoding=self.encoding)))

        except IOError:
            txt = \
                _("Error opening file {filepath}.").format(filepath=self.path)
            try:
                post_command_event(self.main_window, self.StatusBarMsg,
                                   text=txt)
            except TypeError:
                # The main window does not exist any more
                pass

            return False
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')
174731
def save(self, data, fname, header=None):
        
        write_csv(fname, data, self.sep, self.fmt, header)
        self.fnames.add(getattr(fname, 'name', fname))
915654
def write(self, data):
        """"""
        cnpj, data = data

        path = os.path.join(self.output, '%s.json' % cnpj)
        with open(path, 'w') as f:
            json.dump(data, f, encoding='utf-8')
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)
1259777
public void writeFile(String fn, HttpServletResponse res) {

        ValidationFileUtil.initFileSendHeader(res, ValidationFileUtil.getEncodingFileName(fn + ".xls"), null);

        try {
            this.workBook.write(res.getOutputStream());
        } catch (IOException e) {
            throw new ValidationLibException("workbook write error  : " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR, e);
        }
    }
706004
def to_csv(self, file):
        

        file.write("time,value\n")
        for t,v in self:
            file.write("%f,%f\n"% (t, v))
410350
def _write_data(data, fp):
    """"""
    fp.write("@data\n")

    def to_str(x):
        if pandas.isnull(x):
            return '?'
        else:
            return str(x)

    data = data.applymap(to_str)
    n_rows = data.shape[0]
    for i in range(n_rows):
        str_values = list(data.iloc[i, :].apply(_check_str_array))
        line = ",".join(str_values)
        fp.write(line)
        fp.write("\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