Write a header structure into a B1 logfile.

    Inputs:
        filename: name of the file.
        data: header dictionary

    Notes:
        exceptions pass through to the caller.
964272
def writeB1logfile(filename, data):
    
    allkeys = list(data.keys())
    f = open(filename, 'wt', encoding='utf-8')
    for ld in _logfile_data:  # process each line
        linebegin = ld[0]
        fieldnames = ld[1]
        # set the default formatter if it is not given
        if len(ld) < 3:
            formatter = str
        elif ld[2] is None:
            formatter = str
        else:
            formatter = ld[2]
        # this will contain the formatted values.
        formatted = ''
        if isinstance(fieldnames, str):
            # scalar field name, just one field. Formatter should be a
            # callable.
            if fieldnames not in allkeys:
                # this field has already been processed
                continue
            try:
                formatted = formatter(data[fieldnames])
            except KeyError:
                # field not found in param structure
                continue
        elif isinstance(fieldnames, tuple):
            # more than one field names in a tuple. In this case, formatter can
            # be a tuple of callables...
            if all([(fn not in allkeys) for fn in fieldnames]):
                # if all the fields have been processed:
                continue
            if isinstance(formatter, tuple) and len(formatter) == len(fieldnames):
                formatted = ' '.join([ft(data[fn])
                                      for ft, fn in zip(formatter, fieldnames)])
            # ...or a single callable...
            elif not isinstance(formatter, tuple):
                formatted = formatter([data[fn] for fn in fieldnames])
            # ...otherwise raise an exception.
            else:
                raise SyntaxError('Programming error: formatter should be a scalar or a tuple\
of the same length as the field names in logfile_data.')
        else:  # fieldnames is neither a string, nor a tuple.
            raise SyntaxError(
                'Invalid syntax (programming error) in logfile_data in writeparamfile().')
        # try to get the values
        linetowrite = linebegin + ':\t' + formatted + '\n'
        f.write(linetowrite)
        if isinstance(fieldnames, tuple):
            for fn in fieldnames:  # remove the params treated.
                if fn in allkeys:
                    allkeys.remove(fn)
        else:
            if fieldnames in allkeys:
                allkeys.remove(fieldnames)
    # write untreated params
    for k in allkeys:
        linetowrite = k + ':\t' + str(data[k]) + '\n'
        f.write(linetowrite)

    f.close()
1072948
def _write_headers(self, headers):
        
        if headers:
            for name in sorted(headers.keys()):
                yield name.encode("ascii")
                yield b': '
                yield headers[name].encode("ascii")
                yield CRLF
        yield CRLF
331086
def write(self,fileName):
        '''
        '''
        f = open(fileName, 'ab')
        f.write('%s%s' % (self.polarisText,
                          Synset.linebreak)
                )
        f.close()
1344001
private void writePendingToFile() throws java.io.IOException, InternalLogException, LogIncompatibleException
    {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "writePendingToFile");

        synchronized (_pendingWriteList)
        {
            LogRecord[] records = (LogRecord[]) _pendingWriteList.toArray(new LogRecord[0]);

            // Don't use vectored IO unless we're told to.
            if (!Boolean.getBoolean("com.ibm.ws.recoverylog.spi.UseVectoredIO"))
            {
                // Put the file header at the front of the list
                ByteBuffer header = (ByteBuffer) _fileBuffer.duplicate().position(0).limit(_logFileHeader.length());
                _fileChannel.write(header, 0);

                // Write the remainder of the list
                for (int i = 0; i < records.length; i++)
                {
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Performing write at position " + records[i].absolutePosition());
                    _fileChannel.write((ByteBuffer) records[i]._buffer.flip(), records[i].absolutePosition());
                }
            }
            else
            {
                // Sort the records into ascending order based on their absolute
                // position in the file.  We're going to try and keep the disk
                // moving forward.
                Arrays.sort(records, _recordComparator);

                // Now separate the records into two arrays:
                //   o ByteBuffers of data
                //   o Absolute File positions
                ByteBuffer[] buffers = new ByteBuffer[records.length + 1];
                int[] positions = new int[records.length + 1];

                for (int i = 0; i < records.length; i++)
                {
                    buffers[i + 1] = (ByteBuffer) records[i]._buffer.flip();
                    positions[i + 1] = records[i].absolutePosition();
                }

                // Put the file header at the front of the list
                buffers[0] = (ByteBuffer) _fileBuffer.duplicate().position(0).limit(_logFileHeader.length());
                positions[0] = 0;

                // Here's where we go through the list and attempt to write
                // batches of adjacent records using vectored I/O.
                int idx = 0;
                while (idx < buffers.length)
                {
                    int min = idx;
                    int max = idx;

                    // Somewhere in the middle
                    while (max <= (buffers.length - 2))
                    {
                        if (positions[max + 1] == (positions[max] + buffers[max].remaining()))
                            max++;
                    }

                    // Do the actual writes                    
                    _fileChannel.position(positions[min]);
                    _fileChannel.write(buffers, min, (max - min + 1));

                    // Go back and find the next batch
                    idx = max + 1;
                }
            }

            // Cleanup the pending write list for the next force
            _pendingWriteList.clear();
        }

        if (tc.isEntryEnabled())
            Tr.exit(tc, "writePendingToFile");
    }
652683
def _write_header(self):
        """"""
        for line in self.header.lines:
            print(line.serialize(), file=self.stream)
        if self.header.samples.names:
            print(
                "\t".join(list(parser.REQUIRE_SAMPLE_HEADER) + self.header.samples.names),
                file=self.stream,
            )
        else:
            print("\t".join(parser.REQUIRE_NO_SAMPLE_HEADER), file=self.stream)
1284375
def write_file(filename, content):
    
    with open_file(filename, 'w') as f:
        f.write(content)

    file_prepender(filename)
419257
def _write_to_file(self, filename, bytesvalue):
        """"""
        fh, tmp = tempfile.mkstemp()
        with os.fdopen(fh, self._flag) as f:
            f.write(self._dumps(bytesvalue))
        rename(tmp, filename)
        os.chmod(filename, self._mode)
977220
def write(self, filename, append=True):
        
        header = ' '.join(['# User:', getpass.getuser(),
                           '\n# Creation date:', str(UTCDateTime()),
                           '\n# EQcorrscan version:',
                           str(eqcorrscan.__version__),
                           '\n\n\n'])
        if append:
            f = open(filename, 'a')
        else:
            f = open(filename, 'w')
            f.write(header)
        parameters = self.__dict__
        f.write(str(parameters))
        f.write('\n')
        f.close()
        return
1227543
def push_header(self, filename):
        
        # open file and read it all
        with open(filename, "r") as infile:
            content = infile.read()

        # push header
        content = self.__header + content

        # re-write file with the header
        with open(filename, "w") as outfile:
            outfile.write(content)
264218
def write(filename, data):
    
    with open(filename, 'w') as fh:
        fh.write(bibdatabase2bibtex(data))
1156152
def __write_data_col_header(self, l, pc):
        
        count = len(l)
        if pc == "chron":
            self.noaa_txt += "# "
        for name in l:
            # last column - spacing not important
            if count == 1:
                self.noaa_txt += "{}\t".format(name)
            # all [:-1] columns - fixed spacing to preserve alignment
            else:
                self.noaa_txt += "{:<15}".format(name)
                count -= 1

        self.noaa_txt += '\n'
467129
def print_data_to_file(data, file_name):
    
    try:
        with open(file_name, 'w') as output_file:
            print >>output_file, "\t".join(data.dtype.names)
            for row in data:
                print >>output_file, "\t".join(map(str, row))
    except IOError:
        msg = "{}: can't write file".format(file_name)
        raise ProgramError(msg)
389661
def writeHeaderlet(self,**kwargs):
        
        # Insure filehandle is open and available...
        self.openFile()

        pars = kwargs.copy()
        rms_pars = self.fit['rms_keys']

        str_kw = ['descrip','history','author','hdrfile']
        for kw in str_kw:
            if pars[kw] == '': pars[kw] = None

        # Call function with properly interpreted input parameters
        # Syntax: write_headerlet(filename, hdrname, output, sciext='SCI',
        #                    wcsname=None, wcskey=None, destim=None,
        #                    sipname=None, npolfile=None, d2imfile=None,
        #                    author=None, descrip=None, history=None,
        #                    rms_ra=None, rms_dec=None, nmatch=None, catalog=None,
        #                    attach=True, clobber=False):
        headerlet.write_headerlet(self._im.hdu, pars['hdrname'],
                output=pars['hdrfile'],
                wcsname=None, wcskey=self.next_key, destim=None,
                sipname=None, npolfile=None, d2imfile=None,
                author=pars['author'], descrip=pars['descrip'],
                history=pars['history'],
                nmatch=rms_pars['NMATCH'],catalog=pars['catalog'],
                attach=pars['attach'], clobber=pars['clobber']
            )
1121246
protected long writeHeader(java.io.RandomAccessFile logFile)
                    throws ObjectManagerException
    {
        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.entry(this,
                        cclass,
                        "writeHeader",
                        new Object[] { logFile, new Integer(instanceVersion), new Byte(sectorByte),
                                      new Long(startByteAddress), new Long(fileSize) }
                            );

        ObjectManagerByteArrayOutputStream logHeaderStream = new ObjectManagerByteArrayOutputStream(headerLength);
        java.io.DataOutputStream logHeader = new java.io.DataOutputStream(logHeaderStream);

        // Create the data in the log headerBuffer.
        try {
            logHeader.writeByte(0); // Skip over sector byte, for saving sector bits.
            logHeader.writeInt(instanceVersion);
            logHeader.writeByte(sectorByte); // Byte [5].
            logHeader.writeChars(signature);
            logHeader.writeLong(startByteAddress);
            logHeader.writeLong(fileSize);
            logHeader.writeLong(++headerSequence);
            headerWriteTime = System.currentTimeMillis();
            logHeader.writeLong(headerWriteTime);

        } catch (java.io.IOException exception) {
            // No FFDC Code Needed.
            ObjectManager.ffdc.processException(this, cclass, "writeHeader", exception, "1:265:1.8");

            if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
                trace.exit(this,
                           cclass,
                           "writeHeader",
                           exception);
            throw new PermanentIOException(this,
                                           exception);
        } // catch java.io.IOException.

        long filePosition = 0;
        byte[] headerBuffer = logHeaderStream.getBuffer();
        // Set the sector bits in the header to be consistent with the sector bits starting 
        // at the start byte address. This is not much use for validating the header has been
        // written completely because we may rewrite it several times without changing the
        // sector bits, however it does help check that the file is a valid log file.
        // Since we only have data in the first sector, in is only really necessary
        // for the first sector to be written successfully. 
        FileLogOutput.setSectorBits(headerBuffer, 0, sectorByte);

        try {
            logFile.seek(0); // Start writing at the head of the file.
            // Write two LogHeaders.
            for (int i = 0; i < 2; i++) {
                logFile.write(headerBuffer,
                              0,
                              headerLength);
                filePosition = filePosition + headerLength;
            } // for 2 log headers.

        } catch (java.io.IOException exception) {
            // No FFDC Code Needed.
            ObjectManager.ffdc.processException(this, cclass, "writeHeader", exception, "1:298:1.8");

            if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
                trace.exit(this,
                           cclass,
                           "writeHeader",
                           exception);
            throw new PermanentIOException(this,
                                           exception);
        } // catch java.io.IOException.

        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.exit(this,
                       cclass,
                       "writeHeader",
                       new Object[] { new Long(filePosition), new Long(headerSequence), new java.util.Date(headerWriteTime) });
        return filePosition;
    }
1019693
def write(self, file_or_filename):
        
        if isinstance(file_or_filename, basestring):
            file = None
            try:
                file = open(file_or_filename, "wb")
            except Exception, detail:
                logger.error("Error opening %s." % detail)
            finally:
                if file is not None:
                    self._write_data(file)
                    file.close()
        else:
            file = file_or_filename
            self._write_data(file)

        return file
232367
def write_file_lines(self, filename, contents):
        
        with open(filename, 'wb') as f:
            self.log.debug(contents)
            f.writelines(contents)
200560
def setLog(self, fileName, writeName=False):
        
        self.log = 1
        self.logFile = fileName
        self._logPtr = open(fileName, "w")
        if writeName:
            self._namePtr = open(fileName + ".name", "w")