Example #1
0
def _get_file_mode(filename, default='copyonwrite'):
    """
    Allow file object to already be opened in any of the valid modes and
    and leave the file in the same state (opened or closed) as when
    the function was called.
    """

    mode = default
    closed = True

    if hasattr(filename, 'closed'):
        closed = filename.closed
    elif hasattr(filename, 'fileobj') and filename.fileobj is not None:
        closed = filename.fileobj.closed

    if (isfile(filename) or
        isinstance(filename, gzip.GzipFile) and not closed):
        if isinstance(filename, gzip.GzipFile):
            file_mode = filename.fileobj.mode
        else:
            file_mode = filename.mode

        for key, val in PYTHON_MODES.iteritems():
            if val == file_mode:
                mode = key
                break

    return mode, closed
Example #2
0
    def writeto(self, fileobj, output_verify='exception', clobber=False,
                checksum=False):
        """
        Write the `HDUList` to a new file.

        Parameters
        ----------
        fileobj : file path, file object or file-like object
            File to write to.  If a file object, must be opened for
            append (ab+).

        output_verify : str
            Output verification option.  Must be one of ``"fix"``,
            ``"silentfix"``, ``"ignore"``, ``"warn"``, or
            ``"exception"``.  See :ref:`verify` for more info.

        clobber : bool
            When `True`, overwrite the output file if exists.

        checksum : bool
            When `True` adds both ``DATASUM`` and ``CHECKSUM`` cards
            to the headers of all HDU's written to the file.
        """

        if (len(self) == 0):
            warnings.warn("There is nothing to write.")
            return

        self.verify(option=output_verify)

        # check if the file object is closed
        closed = fileobj_closed(fileobj)
        fmode = fileobj_mode(fileobj) or 'ab+'
        filename = fileobj_name(fileobj)

        # check if the output file already exists
        if (isfile(fileobj) or
            isinstance(fileobj, (basestring, gzip.GzipFile))):
            if (os.path.exists(filename) and os.path.getsize(filename) != 0):
                if clobber:
                    warnings.warn("Overwriting existing file '%s'." % filename)
                    if not closed:
                        fileobj.close()
                    os.remove(filename)
                else:
                    raise IOError("File '%s' already exists." % filename)
        elif (hasattr(fileobj, 'len') and fileobj.len > 0):
            if clobber:
                warnings.warn("Overwriting existing file '%s'." % filename)
                name.truncate(0)
            else:
                raise IOError("File '%s' already exists." % filename)

        # make sure the EXTEND keyword is there if there is extension
        self.update_extend()

        mode = 'copyonwrite'
        for key, val in PYTHON_MODES.iteritems():
            if val == fmode:
                mode = key
                break

        hdulist = fitsopen(fileobj, mode=mode)

        for hdu in self:
            hdu._prewriteto(checksum=checksum)
            try:
                hdu._writeto(hdulist.__file)
            finally:
                hdu._postwriteto()
        hdulist.close(output_verify=output_verify, closed=closed)