Write a table to a file.

    Parameters
    ----------
    table : Table
        Table to be written

    filename : str
        Destination for saving table.

    Returns
    -------
    None
344330
def write_table(table, filename):
    
    try:
        if os.path.exists(filename):
            os.remove(filename)
        table.write(filename)
        log.info("Wrote {0}".format(filename))
    except Exception as e:
        if "Format could not be identified" not in e.message:
            raise e
        else:
            fmt = os.path.splitext(filename)[-1][1:].lower()  # extension sans '.'
            raise Exception("Cannot auto-determine format for {0}".format(fmt))
    return
40639
def to_file( Class, dict, file, is_little_endian=True ):
        
        io = BinaryFileWriter( file, is_little_endian=is_little_endian )
        start_offset = io.tell()
        # Header is of fixed length
        io.seek( start_offset + ( 8 * 256 ) )
        # For each item, key and value length (written as length prefixed
        # strings). We also calculate the subtables on this pass.
        # NOTE: This requires the key and value be byte strings, support for
        #       dealing with encoding specific value types should be
        #       added to this wrapper
        subtables = [ [] for i in range(256) ]
        for key, value in dict.items():
            pair_offset = io.tell()
            io.write_uint32( len( key ) )
            io.write_uint32( len( value ) )
            io.write( key )
            io.write( value )
            hash = cdbhash( key )
            subtables[ hash % 256 ].append( ( hash, pair_offset ) )
        # Save the offset where the subtables will start
        subtable_offset = io.tell()
        # Write subtables
        for subtable in subtables:
            if len( subtable ) > 0:
                # Construct hashtable to be twice the size of the number
                # of items in the subtable, and built it in memory
                ncells = len( subtable ) * 2
                cells = [ (0,0) for i in range( ncells ) ]
                for hash, pair_offset in subtable:
                    index = ( hash >> 8 ) % ncells
                    while cells[index][1] != 0:
                        index = ( index + 1 ) % ncells
                    # Guaranteed to find a non-empty cell
                    cells[index] = ( hash, pair_offset )
                # Write subtable
                for hash, pair_offset in cells:
                    io.write_uint32( hash )
                    io.write_uint32( pair_offset )
        # Go back and write the header
        end_offset = io.tell()
        io.seek( start_offset )
        index = subtable_offset
        for subtable in subtables:
            io.write_uint32( index )
            io.write_uint32( len( subtable * 2 ) )
            # For each cell in the subtable, a hash and a pointer to a value
            index += ( len( subtable ) * 2 ) * 8
        # Leave fp at end of cdb
        io.seek( end_offset )
843789
def capture_table(table)
      return 'none' if table.size == 1 # the first row is for column titles
      $stdout = StringIO.new  # start capturing the output
      print_table(table.map{ |row| row.map(&:to_s) })
      output = $stdout
      $stdout = STDOUT        # restore normal output
      return output.string
    end
143039
def _create_table(self):
        '''
        
        '''
        self._cursor.execute('''
            CREATE TABLE IF NOT EXISTS %(name)s ( %(fields)s )
        ''' % {
            'name': self._name,
            'fields': ','.join('%s %s' % (k, v) for (k, v) in self._fields)
        })
        self._connection.commit()
211738
def export_to_json(
    table, filename_or_fobj=None, encoding="utf-8", indent=None, *args, **kwargs
):
    
    # TODO: will work only if table.fields is OrderedDict

    fields = table.fields
    prepared_table = prepare_to_export(table, *args, **kwargs)
    field_names = next(prepared_table)
    data = [
        {
            field_name: _convert(value, fields[field_name], *args, **kwargs)
            for field_name, value in zip(field_names, row)
        }
        for row in prepared_table
    ]

    result = json.dumps(data, indent=indent)
    if type(result) is six.text_type:  # Python 3
        result = result.encode(encoding)

    if indent is not None:
        # clean up empty spaces at the end of lines
        result = b"\n".join(line.rstrip() for line in result.splitlines())

    return export_data(filename_or_fobj, result, mode="wb")
1022049
def save(self, filename=None):
        
        if filename is None:
            filename = self.filename
        with open(filename, 'wb') as f:
            f.write(self.data)
910983
protected void writeTableInit(Table t) throws IOException {

        tableRowCount = 0;

        rowOut.reset();
        rowOut.writeSize(0);
        rowOut.writeString(t.getName().name);
        rowOut.writeInt(INSERT_WITH_SCHEMA);
        rowOut.writeString(t.getSchemaName().name);
        rowOut.writeIntData(rowOut.size(), 0);
        fileStreamOut.write(rowOut.getOutputStream().getBuffer(), 0,
                            rowOut.size());
    }
421077
def write_table(self):
        

        tags = _get_tags_module()

        with self._logger:
            self._verify_property()
            self._preprocess()

            if typepy.is_not_null_string(self.table_name):
                self._table_tag = tags.table(id=sanitize_python_var_name(self.table_name))
                self._table_tag += tags.caption(MultiByteStrDecoder(self.table_name).unicode_str)
            else:
                self._table_tag = tags.table()

            try:
                self._write_header()
            except EmptyHeaderError:
                pass

            self._write_body()
552413
def write_file(self, filename):
        
        with open(filename, "w") as f:
            f.write(self.__str__())
605454
protected void writeToFile(TableMeta tableMeta) throws IOException {
		File dir = new File(modelOutputDir);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		
		String target = modelOutputDir + File.separator + tableMeta.modelName + ".java";
		
		File file = new File(target);
		if (file.exists()) {
			return ;	// 若 Model 存在，不覆盖
		}
		
		OutputStreamWriter osw = null;
		try {
			osw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
			osw.write(tableMeta.modelContent);
		}
		finally {
			if (osw != null) {
				osw.close();
			}
		}
	}
1120433
def save_to_file(self, fname):
        
        with open(fname, 'w') as f:
            f.write(str(self))
433802
def save(self, filename):
        
        gz = filename.endswith('.gz')
        ligolw_utils.write_filename(self.outdoc, filename, gz=gz)
752150
def table(args):
    
    import csv

    p = OptionParser(table.__doc__)
    p.set_sep(sep=",")
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    htmlfile, = args
    page = open(htmlfile).read()
    soup = BeautifulSoup(page)

    for i, tabl in enumerate(soup.findAll('table')):
        nrows = 0
        csvfile = htmlfile.rsplit(".", 1)[0] + ".{0}.csv".format(i)
        writer = csv.writer(open(csvfile, "w"), delimiter=opts.sep)
        rows = tabl.findAll('tr')
        for tr in rows:
            cols = tr.findAll('td')
            if not cols:
                cols = tr.findAll('th')

            row = []
            for td in cols:
                try:
                    cell = "".join(td.find(text=True))
                    cell = unescape(cell)
                except TypeError:
                    cell = ""
                row.append(cell)
            writer.writerow(row)
            nrows += 1
        logging.debug("Table with {0} rows written to `{1}`.".format(nrows, csvfile))
593185
def make_table(file_dict):
        """"""
        col_key = Column(name='key', dtype=int)
        col_path = Column(name='path', dtype='S256')
        col_creator = Column(name='creator', dtype=int)
        col_timestamp = Column(name='timestamp', dtype=int)
        col_status = Column(name='status', dtype=int)
        col_flags = Column(name='flags', dtype=int)
        columns = [col_key, col_path, col_creator,
                   col_timestamp, col_status, col_flags]
        table = Table(data=columns)
        for val in file_dict.values():
            val.append_to_table(table)
        return table
428879
def write_file(self, filename):
        
        writer = self.__str__()[:-1].decode('utf-8')
        with open(filename, 'w') as fout:
            fout.write(writer)
1020325
public long writeToTable(String datasetName, String tableName, String csvData)
      throws IOException, InterruptedException, TimeoutException {
    // [START ]
    TableId tableId = TableId.of(datasetName, tableName);
    WriteChannelConfiguration writeChannelConfiguration =
        WriteChannelConfiguration.newBuilder(tableId).setFormatOptions(FormatOptions.csv()).build();
    TableDataWriteChannel writer = bigquery.writer(writeChannelConfiguration);
    // Write data to writer
    try {
      writer.write(ByteBuffer.wrap(csvData.getBytes(Charsets.UTF_8)));
    } finally {
      writer.close();
    }
    // Get load job
    Job job = writer.getJob();
    job = job.waitFor();
    LoadStatistics stats = job.getStatistics();
    return stats.getOutputRows();
    // [END ]
  }
604896
def records(self):
        
        output = tempfile.NamedTemporaryFile(suffix='.json')
        try:
            log.info("Loading table from (%s)...", self._obj)
            shutil.copyfileobj(self.fh(), output)
            output.seek(0)

            for line in output.file:
                yield json.loads(line, object_hook=json_hook)

        finally:
            try:
                output.close()
            except:
                pass