Exemple #1
0
def open_read_file(file_name=None, dir=None, verbosity=1):
    """Open the file 'file' and return all the data.

    @keyword file_name: The name of the file to extract the data from.
    @type file_name:    str
    @keyword dir:       The path where the file is located.  If None, then the current directory is assumed.
    @type dir:          str
    @keyword verbosity: The verbosity level.
    @type verbosity:    int
    @return:            The open file object.
    @rtype:             file object
    """

    # A file descriptor object.
    if is_filetype(file_name):
        # Nothing to do here!
        return file_name

    # Invalid file name.
    if not file_name and not isinstance(file_name, str):
        raise RelaxError("The file name " + repr(file_name) + " " +
                         repr(type(file_name)) +
                         " is invalid and cannot be opened.")

    # File path.
    file_path = get_file_path(file_name, dir)

    # Test if the file exists and determine the compression type.
    compress_type, file_path = determine_compression(file_path)

    # Open the file for reading.
    try:
        # Print out.
        if verbosity:
            print("Opening the file " + repr(file_path) + " for reading.")

        # Uncompressed text.
        if compress_type == 0:
            file_obj = open(file_path, 'r')

        # Bzip2 compressed text.
        elif compress_type == 1:
            file_obj = bz2_open(file=file_path, mode='r')

        # Gzipped compressed text.
        elif compress_type == 2:
            file_obj = gz_open(file=file_path, mode='r')

    # Cannot open.
    except IOError:
        message = sys.exc_info()[1]
        raise RelaxError("Cannot open the file " + repr(file_path) + ".  " +
                         message.args[1] + ".")

    # Return the opened file.
    return file_obj
Exemple #2
0
def open_write_file(file_name=None,
                    dir=None,
                    force=False,
                    compress_type=0,
                    verbosity=1,
                    return_path=False):
    """Function for opening a file for writing and creating directories if necessary.

    @keyword file_name:     The name of the file to extract the data from.
    @type file_name:        str
    @keyword dir:           The path where the file is located.  If None, then the current directory is assumed.
    @type dir:              str
    @keyword force:         Boolean argument which if True causes the file to be overwritten if it already exists.
    @type force:            bool
    @keyword compress_type: The compression type.  The integer values correspond to the compression type: 0, no compression; 1, Bzip2 compression; 2, Gzip compression.  If no compression is given but the file name ends in '.gz' or '.bz2', then the compression will be automatically set.
    @type compress_type:    int
    @keyword verbosity:     The verbosity level.
    @type verbosity:        int
    @keyword return_path:   If True, the function will return a tuple of the file object and the full file path.
    @type return_path:      bool
    @return:                The open, writable file object and, if the return_path is True, then the full file path is returned as well.
    @rtype:                 writable file object (if return_path, then a tuple of the writable file and the full file path)
    """

    # No file name?
    if file_name == None:
        raise RelaxError("The name of the file must be supplied.")

    # A file descriptor object.
    if is_filetype(file_name):
        # Nothing to do here!
        return file_name

    # Something pretending to be a file object.
    if hasattr(file_name, 'write'):
        # Nothing to do here!
        return file_name

    # The null device.
    if search('devnull', file_name):
        # Print out.
        if verbosity:
            print("Opening the null device file for writing.")

        # Open the null device.
        file_obj = open(devnull, 'w')

        # Return the file.
        if return_path:
            return file_obj, None
        else:
            return file_obj

    # Create the directories.
    mkdir_nofail(dir, verbosity=0)

    # File path.
    file_path = get_file_path(file_name, dir)

    # If no compression is supplied, determine the compression to be used from the file extension.
    if compress_type == 0:
        if search('.bz2$', file_path):
            compress_type = 1
        elif search('.gz$', file_path):
            compress_type = 2

    # Bzip2 compression.
    if compress_type == 1 and not search('.bz2$', file_path):
        # Bz2 module exists.
        if bz2:
            file_path = file_path + '.bz2'

        # Switch to gzip compression.
        else:
            warn(
                RelaxWarning(
                    "Cannot use Bzip2 compression, using gzip compression instead.  "
                    + bz2_module_message + "."))
            compress_type = 2

    # Gzip compression.
    if compress_type == 2 and not search('.gz$', file_path):
        file_path = file_path + '.gz'

    # Fail if the file already exists and the force flag is set to 0.
    if access(file_path, F_OK) and not force:
        raise RelaxFileOverwriteError(file_path, 'force flag')

    # Open the file for writing.
    try:
        # Print out.
        if verbosity:
            print("Opening the file " + repr(file_path) + " for writing.")

        # Uncompressed text.
        if compress_type == 0:
            file_obj = open(file_path, 'w')

        # Bzip2 compressed text.
        elif compress_type == 1:
            file_obj = bz2_open(file=file_path, mode='w')

        # Gzipped compressed text.
        elif compress_type == 2:
            file_obj = gz_open(file=file_path, mode='w')

    # Cannot open.
    except IOError:
        message = sys.exc_info()[1]
        raise RelaxError("Cannot open the file " + repr(file_path) + ".  " +
                         message.args[1] + ".")

    # Return the opened file.
    if return_path:
        return file_obj, file_path
    else:
        return file_obj