On Python 3 opens a file in text mode by using fs encoding and
    a proper en/decoding errors handler.
    On Python 2 this is just an alias for open(name, 'rt').
328825
def _open_text(fname, **kwargs):
    
    if PY3:
        kwargs.setdefault('encoding', ENCODING)
        kwargs.setdefault('errors', ENCODING_ERRS)
    return open(fname, "rt", **kwargs)
517081
def is_binary(f):
    """"""
    # NOTE: order matters here. We don't bail on Python 2 just yet. Both
    # codecs.open() and io.open() can open in text mode, both set the encoding
    # attribute. We must do that check first.

    # If it has a decoding attribute with a value, it is text mode.
    if getattr(f, "encoding", None):
        return False

    # Python 2 makes no further distinction.
    if not PY3:
        return True

    # If the file has a mode, and it contains b, it is binary.
    try:
        if 'b' in getattr(f, 'mode', ''):
            return True
    except TypeError:
        import gzip
        if isinstance(f, gzip.GzipFile):
            return True  # in gzip mode is an integer
        raise

    # Can we sniff?
    try:
        f.seek(0, os.SEEK_CUR)
    except (AttributeError, IOError):
        return False

    # Finally, let's sniff by reading a byte.
    byte = f.read(1)
    f.seek(-1, os.SEEK_CUR)
    return hasattr(byte, 'decode')
1082897
def open(self, name, mode='r', compression=None):
        

        if compression == 'use_ext':
            self.get_compression_type(name)
        else:
            self.ctype = compression

        if not self.ctype:
            self.fp = open(name, mode)
        elif self.ctype == 'gzip':
            self.fp = gzip.open(name, mode + 't')
        elif self.ctype == 'bzip2':
            try:
                # Python 3 supports opening bzip2 files in text mode
                # therefore, we prefer to open them this way
                self.fp = bz2.open(name, mode + 't')
            except:
                # BZ2File opens a file in binary mode
                # thus, we have to use codecs.getreader()
                # to be able to use it in text mode
                self.fp_extra = bz2.BZ2File(name, mode)

                if mode == 'r':
                    self.fp = codecs.getreader('ascii')(self.fp_extra)
                else:  # mode == 'w'
                    self.fp = codecs.getwriter('ascii')(self.fp_extra)
        else:  # self.ctype == 'lzma'
            # LZMA is available in Python 2 only if backports.lzma is installed
            # Python 3 supports it by default
            assert lzma_present, 'LZMA compression is unavailable.'
            self.fp = lzma.open(name, mode=mode + 't')
96347
def read(self, mode='r', *, buffering=-1, encoding=None, newline=None):
        '''  '''
        with self.open(mode=mode, buffering=buffering, encoding=encoding, newline=newline) as fp:
            return fp.read()
746365
def _open(file_, mode='r'):
  """"""
  if isinstance(file_, string_types):
    _, ext = path.splitext(file_)
    if ext in {'.bz2', '.gz'}:
      s = tarfile.open(file_)
      return s.extractfile(s.next())
    else:
      return open(file_, mode)
  return file_
96260
def open_compressed(filename, mode="r", encoding=None):
    ""

    # TODO: integrate this function in the library itself, using
    # get_filename_and_fobj
    binary_mode = "b" in mode
    extension = str(filename).split(".")[-1].lower()
    if binary_mode and encoding:
        raise ValueError("encoding should not be specified in binary mode")

    if extension == "xz":
        if lzma is None:
            raise RuntimeError("lzma support is not installed")

        fobj = lzma.open(filename, mode=mode)
        if binary_mode:
            return fobj
        else:
            return io.TextIOWrapper(fobj, encoding=encoding)

    elif extension == "gz":
        fobj = gzip.GzipFile(filename, mode=mode)
        if binary_mode:
            return fobj
        else:
            return io.TextIOWrapper(fobj, encoding=encoding)

    elif extension == "bz2":
        if bz2 is None:
            raise RuntimeError("bzip2 support is not installed")

        if binary_mode:  # ignore encoding
            return bz2.open(filename, mode=mode)
        else:
            if "t" not in mode:
                # For some reason, passing only mode='r' to bzip2 is equivalent
                # to 'rb', not 'rt', so we force it here.
                mode += "t"
            return bz2.open(filename, mode=mode, encoding=encoding)

    else:
        if binary_mode:
            return open(filename, mode=mode)
        else:
            return open(filename, mode=mode, encoding=encoding)
196381
def open_file(filename, mode='rb'):
    
    if (('r' not in mode or hasattr(filename, 'read')) and
        (('a' not in mode and 'w' not in mode) or hasattr(filename, 'write')) and
        hasattr(filename, '__iter__')):
        return filename
    elif isinstance(filename, string_type):
        if filename == '-' and 'r' in mode:
            if PY3:
                return sys.stdin.buffer
            return sys.stdin
        elif filename == '-' and ('w' in mode or 'a' in mode):
            if PY3:
                return sys.stdout.buffer
            return sys.stdout
        if filename.lower().count('.zip:'):
            assert 'r' in mode
            assert filename.count(':') == 1
            import zipfile
            zipped_file = zipfile.ZipFile(filename.split(':')[0])
            unzipped_file = zipped_file.open(filename.split(':')[1], 'r')
            zipped_file.close()
            return unzipped_file
        elif filename.lower().endswith('.gz'):
            import gzip
            return gzip.open(filename, mode)
        elif filename.lower().endswith('.xz'):
            import lzma
            tmp = lzma.LZMAFile(filename, mode)
            dir(tmp)
            return tmp
        else:
            return open(filename, mode)
    else:
        raise Exception('Unknown type for argument filename')
27988
def read(fname):
    
    fpath = os.path.join(os.path.dirname(__file__), fname)
    with codecs.open(fpath, 'r', 'utf8') as fhandle:
        return fhandle.read().strip()
894024
def open(self, mode='rb'):
        
        fs, path = self._get_fs()
        return fs.open(path, mode=mode)
912529
def open_without_clobber(name, *args):
    
    fd = None
    count = 1
    orig_name = name
    while fd is None:
        try:
            fd = os.open(name, os.O_CREAT | os.O_EXCL, 0o666)
        except OSError as err:
            if err.errno == errno.EEXIST:
                name = "%s.%i" % (orig_name, count)
                count += 1
            else:
                raise IOError(err.errno, err.strerror, err.filename)
    fobj = open(name, *args)
    if fd != fobj.fileno():
        os.close(fd)
    return fobj
463326
def open(self, filename, mode='r', bufsize=-1):
        
        sftp_client = self.open_sftp()
        return sftp_client.open(filename, mode, bufsize)
996272
def openfile(filename, mode="rt", *args, expanduser=False, expandvars=False,
             makedirs=False, **kwargs):
    """"""
    if filename in ("-", None):
        return sys.stdin if "r" in mode else sys.stdout
    if expanduser:
        filename = os.path.expanduser(filename)
    if expandvars:
        filename = os.path.expandvars(filename)
    if makedirs and ("a" in mode or "w" in mode):
        parentdir = os.path.dirname(filename)
        if not os.path.isdir(parentdir):
            os.makedirs(parentdir)
    if filename.endswith(".gz"):
        if gzip is None:
            raise NotImplementedError
        _open = gzip.open
    elif filename.endswith(".bz2"):
        if bz2 is None:
            raise NotImplementedError
        _open = bz2.open
    elif filename.endswith(".xz") or filename.endswith(".lzma"):
        if lzma is None:
            raise NotImplementedError
        _open = lzma.open
    else:
        _open = open
    return _open(filename, mode, *args, **kwargs)
631422
def atomic_open(filename, mode='w'):
    '''
    
    '''
    if mode in ('r', 'rb', 'r+', 'rb+', 'a', 'ab'):
        raise TypeError('Read or append modes don\'t work with atomic_open')
    kwargs = {
        'prefix': '.___atomic_write',
        'dir': os.path.dirname(filename),
        'delete': False,
    }
    if six.PY3 and 'b' not in mode:
        kwargs['newline'] = ''
    ntf = tempfile.NamedTemporaryFile(mode, **kwargs)
    return _AtomicWFile(ntf, ntf.name, filename)
90582
def read_text_file(filename, encoding="utf-8"):
    
    try:
        with open(filename, 'r', encoding) as f:
            r = f.read()
    except TypeError:
        with open(filename, 'r') as f:
            r = f.read()
    return r
370920
def read_file(self, infile):
        
        try:
            with open(infile, 'rt') as file:
                return file.read()
        except UnicodeDecodeError as e:
            err_exit('Error reading %s: %s' % (infile, e))
        except (IOError, OSError) as e:
            err_exit('Error reading %s: %s' % (infile, e.strerror or e))
216823
def open_file(orig_file_path):
    
    unquoted = unquote(orig_file_path)
    paths = [
        convert_to_platform_safe(orig_file_path),
        "%s/index.html" % (convert_to_platform_safe(orig_file_path)),
        orig_file_path,
        "%s/index.html" % orig_file_path,
        convert_to_platform_safe(unquoted),
        "%s/index.html" % (convert_to_platform_safe(unquoted)),
        unquoted,
        "%s/index.html" % unquoted,
        ]

    file_path = None
    handle = None
    for path in paths:
        try:
            file_path = path
            handle = open(path, "rb")
            break
        except IOError:
            pass

    return handle
892342
def open(filename):
	
	buffer = _builtin_open(filename, 'rb')
	try:
		encoding, lines = detect_encoding(buffer.readline)
		buffer.seek(0)
		text = TextIOWrapper(buffer, encoding, line_buffering=True)
		text.mode = 'r'
		return text
	except:
		buffer.close()
		raise