Write BIOM table to file.

    Parameters
    ----------
    table: biom.table
        an instance of a BIOM table
    biom_fp: string
        filepath to output BIOM table
189539
def write_biom_table(table, biom_fp):
    
    logger = logging.getLogger(__name__)
    logger.debug('write_biom_table to file %s' % biom_fp)
    with biom_open(biom_fp, 'w') as f:
        table.to_hdf5(h5grp=f, generated_by="deblur")
        logger.debug('wrote to BIOM file %s' % biom_fp)
1046881
def write_table_file(self, job_table_file=None, file_table_file=None):
        """"""
        if self._table is None:
            raise RuntimeError("No table to write")
        if self._table_ids is None:
            raise RuntimeError("No ID table to write")
        if job_table_file is not None:
            self._table_file = job_table_file
        if self._table_file is None:
            raise RuntimeError("No output file specified for table")
        write_tables_to_fits(self._table_file, [self._table, self._table_ids], clobber=True,
                             namelist=['JOB_ARCHIVE', 'FILE_IDS'])
        self._file_archive.write_table_file(file_table_file)
248770
def write_file(self, blob, dest):
        '''
        
        '''
        with salt.utils.files.fopen(dest, 'wb+') as fp_:
            blob.stream_data(fp_)
563759
def _write_to_filepath(content, output):
    
    outdir = os.path.dirname(output)
    if outdir and not os.path.exists(outdir):
        os.makedirs(outdir)

    with anytemplate.compat.copen(output, 'w') as out:
        out.write(content)
735824
def _write_method(schema):
    
    def method(
        self,
        filename=None,
        schema=schema,
        taxon_col='uid',
        taxon_annotations=[],
        node_col='uid',
        node_annotations=[],
        branch_lengths=True,
        **kwargs):
        # Use generic write class to write data.
        return _write(
            self._data,
            filename=filename,
            schema=schema,
            taxon_col=taxon_col,
            taxon_annotations=taxon_annotations,
            node_col=node_col,
            node_annotations=node_annotations,
            branch_lengths=branch_lengths,
            **kwargs
        )
    # Update docs
    method.__doc__ = _write_doc_template(schema)
    return method
500491
def table_dump(self, table):
        """"""
        if not table: raise ValueError("no table")

        cmds = []
        logger.info('------- dumping table {}'.format(table))
        cmd = self._get_args(
            "pg_dump",
            "--table={}".format(table),
            #"--data-only",
            "--clean",
            "--no-owner",
            "--column-inserts",
        )
        cmds.append((cmd, {}))

        outfile_path = self._get_outfile_path(table)
        cmds.append(('gzip > "{}"'.format(outfile_path), {"shell": True}))

        #cmd += ' | {}'.format(' | '.join(pipes))
        #cmd += ' > {}'.format(outfile_path)

        self._run_cmds(cmds)
        logger.info('------- dumped table {}'.format(table))
        return True
797208
def write_output_files(self, fh):
    
    for f in self.__output_files:
        print >>fh, "## Job %s generates output file %s" % (self.__name, f)
905035
def write_file(self, fp, data):
        """"""
        with open(fp, 'w') as f:
            f.write(data)
746730
def save(self, savefile):
        
        with open(str(savefile), 'wb') as f:
            self.write_to_fp(f)
            log.debug("Saved to %s", savefile)
254438
def write(self, data_in, data_out, *args, **kwargs):
        
        self._get_tables(data_in)

        self.file_emulation = False
        outputs = []
        self._prepare_outputs(data_out, outputs)
        output = outputs[0]
        for i in xrange(len(self.tables)):
            table = self.tables[i]

            self._write_table(output, table)

        if data_out != output and hasattr(data_out, 'write'):
            output.Flush()
            output.ReOpen('read')
            file_size = output.GetSize()
            buff = bytearray(file_size)
            output.ReadBuffer(buff, file_size)
            data_out.write(buff)

        if self.file_emulation:
            filename = output.GetName()
            output.Close()
835481
def to_file(self, path, precision='%.2g'):
        
        table_info = self.get_table_info()

        def dump_rows(rows):
            if len(rows) > 1:
                for row in rows:
                    csv_writer.writerow(row)
                csv_writer.writerow([])

        with open(path, 'wb') as _f:
            csv_writer = csv.writer(_f)

            state_rows = [['States']]
            state_rows += [['Name', 'Description', 'State', 'Number of Changes']]
            for state in self.states:
                state_rows.append([state.name, table_info[state.name]['description'], state.state, state.count])
            dump_rows(state_rows)

            stat_rows = [['Statistics']]
            stat_rows += [['Name', 'Description', 'Total', 'Average']]
            for stat in self.statistics:
                if stat.name == '__submissions__':
                    continue
                stat_rows.append([stat.name, table_info[stat.name]['description'], stat.count, stat.get_average(0)])
                dump_rows(stat_rows)

            timer_rows = [['Timers']]
            timer_rows += [['Name', 'Description', 'Average Seconds', 'Total Seconds', 'Total Minutes', 'Total Hours', 'Total Days']]
            for timer in self.timers:
                timer_rows.append([timer.name, table_info[timer.name]['description'],
                                   precision % timer.get_average(0), precision % timer.total_seconds, precision % timer.total_minutes,
                                   precision % timer.total_hours, precision % timer.total_days])
                dump_rows(timer_rows)

            sequence_rows = [['Sequences']]
            sequence_rows += [['Name', 'Description', 'Sequence', 'Number of Completions']]
            for sequence in self.sequences:
                checkpoints = '-->'.join(map(str, sequence.get_checkpoints()))
                sequence_rows.append([sequence.name, table_info[sequence.name]['description'], checkpoints, sequence.count])
                dump_rows(sequence_rows)
49529
def write_dna(dna, path):
    '''

    '''
    # Check if path filetype is valid, remember for later
    ext = os.path.splitext(path)[1]
    if ext == '.gb' or ext == '.ape':
        filetype = 'genbank'
    elif ext == '.fa' or ext == '.fasta':
        filetype = 'fasta'
    else:
        raise ValueError('Only genbank or fasta files are supported.')

    # Convert features to Biopython form
    # Information lost on conversion:
    #     specificity of feature type
    #     strandedness
    #     topology
    features = []
    for feature in dna.features:
        features.append(_coral_to_seqfeature(feature))
    # Biopython doesn't like 'None' here
    # FIXME: this is a legacy feature - remove?
    bio_id = dna.id if hasattr(dna, 'id') else ''
    # Maximum length of name is 16
    seq = SeqRecord(Seq(str(dna), alphabet=ambiguous_dna), id=bio_id,
                    name=dna.name[0:16].replace(' ', '_'), features=features,
                    description=dna.name)
    if dna.circular:
        seq.annotations['data_file_division'] = 'circular'
    else:
        seq.annotations['data_file_division'] = 'linear'

    if filetype == 'genbank':
        SeqIO.write(seq, path, 'genbank')
    elif filetype == 'fasta':
        SeqIO.write(seq, path, 'fasta')
201634
def write_file(self, *args, **kwargs):
        
        return self._fdapi.write_file(self.get_path(), *args, **kwargs)
80791
def write_geoms_to_file(self, fp, geoms, names=None):
        """"""
        if fp[-5:] != '.gpkg':
            fp = fp + '.gpkg'
        if names is not None:
            assert len(geoms) == len(names), "Inconsistent length of geometries and names"
        else:
            names = ("Merged geometry {}".format(count) for count in itertools.count())
        meta = {
            'crs': {'no_defs': True, 'ellps': 'WGS84', 'datum': 'WGS84', 'proj': 'longlat'},
            'driver': 'GPKG',
            'schema': {'geometry': 'MultiPolygon', 'properties': {'name': 'str', 'id': 'int'}}
        }
        with fiona.drivers():
            with fiona.open(fp, 'w', **meta) as sink:
                for geom, name, count in zip(geoms, names, itertools.count(1)):
                    sink.write({
                        'geometry': _to_fiona(geom),
                        'properties': {'name': name, 'id': count}
                    })
        return fp
375952
public static void save(CSTable table, File file) throws IOException {
        PrintWriter w = new PrintWriter(file);
        print(table, w);
        w.close();
    }
652592
def _writeContaminantTable(self, session, fileObject, mapTable, contaminants, replaceParamFile):
        
        # Write the contaminant mapping table header
        fileObject.write('%s\n' % (mapTable.name))
        fileObject.write('NUM_CONTAM %s\n' % (mapTable.numContam))

        # Write out each contaminant and it's values
        for contaminant in contaminants:
            fileObject.write(
                '"%s"  "%s"  %s\n' % (contaminant.name, contaminant.indexMap.name, contaminant.outputFilename))

            # Add trailing zeros to values / replacement parameter
            precipConcString = vwp(contaminant.precipConc, replaceParamFile)
            partitionString = vwp(contaminant.partition, replaceParamFile)
            try:
                precipConc = '%.2f' % precipConcString
            except:
                precipConc = '%s' % precipConcString

            try:
                partition = '%.2f' % partitionString
            except:
                partition = '%s' % partitionString

            # Write global variables for the contaminant
            fileObject.write('PRECIP_CONC%s%s\n' % (' ' * 10, precipConc))
            fileObject.write('PARTITION%s%s\n' % (' ' * 12, partition))
            fileObject.write('NUM_IDS %s\n' % contaminant.numIDs)

            # Write value lines
            self._writeValues(session, fileObject, mapTable, contaminant, replaceParamFile)
1271241
def append_to_table(self, table):
        
        table.add_row(dict(path=self.path,
                           key=self.key,
                           creator=self.creator,
                           timestamp=self.timestamp,
                           status=self.status,
                           flags=self.flags))