Return opened file with a specific encoding.
350119
def open_with_encoding(filename,
                       encoding=None, mode='r', limit_byte_check=-1):
    """"""
    if not encoding:
        encoding = detect_encoding(filename, limit_byte_check=limit_byte_check)

    return io.open(filename, mode=mode, encoding=encoding,
                   newline='')
779831
def _set_file_encoding_utf8(filename):
    """"""
    with open(filename, 'r+') as f:
        content = f.read()
        f.seek(0, 0)
        f.write("# -*- coding: utf-8 -*-\n" + content)
1147689
def read_zipfile(self, encoding='utf8'):
        
        from zipfile import ZipFile
        with ZipFile(self.abspath) as zipped:
            for num, zip_name in enumerate(zipped.namelist()):
                return zipped.open(zip_name).read().decode(encoding)
19488
def read(path, encoding="UTF-8"):
    """"""
    with OPEN_FUNC(path, 'rb') as _file:
        cont = _file.read()
        return cont.decode(encoding)
458953
function readFile (file, {encoding='utf8'} = {}) {
	return Q.Promise((resolve, reject) => {
		try {
			FS.readFile(file, {encoding}, (err, data) => {
				try {
					if (err) {
						reject(err);
					} else {
						resolve(data);
					}
				} catch (err) {
					debug.error('Unexpected exception: ', err);
					reject(err);
				}
			});
		} catch (err) {
			reject(err);
		}
	});
}
215372
def _get_encoding(self):
        """"""
        enco = 'utf-8'

        #  Currently only cp1252 is allowed?
        if WIN:
            import ctypes
            codepage = to_text_string(ctypes.cdll.kernel32.GetACP())
            # import locale
            # locale.getpreferredencoding()  # Differences?
            enco = 'cp' + codepage
        return enco
443872
def url_or_file_open(uri):
    """"""
    if (not re.match(r'''\w+:''', uri)):
        uri = 'file:' + uri
    return(urlopen(uri))
513713
def read(path, encoding="utf-8"):
    
    is_gzip = is_gzip_file(path)

    with open(path, "rb") as f:
        if is_gzip:
            return zlib.decompress(f.read()).decode(encoding)
        else:
            return f.read().decode(encoding)
1115244
def get_lines_from_file(filepath, encoding="UTF-8"):
    """"""
    try:
        fd = codecs.open(filepath, 'r', encoding)
        lines = fd.readlines()
    except UnicodeDecodeError:
        # Fall back to 'ISO-8859-1'
        fd = codecs.open(filepath, 'r', 'ISO-8859-1')
        lines = fd.readlines()
    finally:
        fd.close()
    return lines
903285
def process_file(path, processor, encoding='utf-8', mode='rt', *args, **kwargs):
    '''  '''
    if mode not in ('rU', 'rt', 'rb', 'r'):
        raise Exception("Invalid file reading mode")
    with open(path, encoding=encoding, mode=mode, *args, **kwargs) as infile:
        return processor(infile)
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)
1125923
def copen(filepath, flag='r', encoding=None):

    
    if encoding is None:
        encoding = locale.getdefaultlocale()[1]

    return codecs.open(filepath, flag, encoding)
1067003
def open_maybe_binary(filename):
    """"""
    if sys.version_info >= (3, 0):
        data = open(filename, 'rb').read()
        try:
            return data.decode('utf-8')
        except UnicodeDecodeError:
            return data

    return open(filename, 'r').read()
1183177
def read_file(path, encoding='utf-8', *args, **kwargs):
    ''' 
    '''
    if 'mode' in kwargs and kwargs['mode'] == 'rb':
        return process_file(path, processor=lambda x: x.read(),
                            encoding=encoding, *args, **kwargs)
    else:
        return process_file(path, processor=lambda x: to_string(x.read(), encoding),
                            encoding=encoding, *args, **kwargs)
820721
def get_file_encoding(self, file_path, preferred_encoding=None):
        
        _logger().debug('getting encoding for %s', file_path)
        try:
            map = json.loads(self._settings.value('cachedFileEncodings'))
        except TypeError:
            map = {}
        try:
            return map[file_path]
        except KeyError:
            encodings = self.preferred_encodings
            if preferred_encoding:
                encodings.insert(0, preferred_encoding)
            for encoding in encodings:
                _logger().debug('trying encoding: %s', encoding)
                try:
                    with open(file_path, encoding=encoding) as f:
                        f.read()
                except (UnicodeDecodeError, IOError, OSError):
                    pass
                else:
                    return encoding
            raise KeyError(file_path)
831875
def _safe_read(path, length):
    """"""
    if not os.path.exists(os.path.join(HERE, path)):
        return ''
    file_handle = codecs.open(os.path.join(HERE, path), encoding='utf-8')
    contents = file_handle.read(length)
    file_handle.close()
    return contents
794259
def detect_lang(path):
	""""""
	blob = FileBlob(path, os.getcwd())
	if blob.is_text:
		print('Programming language of the file detected: {0}'.format(blob.language.name))
		return blob.language.name
	else:#images, binary and what-have-you won't be pasted
		print('File not a text file. Exiting...')
		sys.exit()