Как узнать кодировку файла python

от admin

Как определить кодировку последовательности байтов в Python

30 октября 2017 г. Archy Просмотров: 29242 RSS 3
Python для начинающих ascii, chardet, chardetect, utf-8, байты в Pyhon

Как определить кодировку последовательности байтов в Python

Как узнать, в какой кодировке записана последовательность байтов? Коротки ответ: никак. Кто-то должен вам сообщить.

В некоторых коммуникационных протоколах и файловых форматах, например HTTP и XML, предусмотрены заголовки, в которых явно указывается, как закодировано содержимое.

Можно быть уверенным, что поток байтов представлен не в кодировке ASCII, если он содержит значения, больше 127, а сам способ построения UTF-8 и UTF-16 исключает определенные последовательности байтов.

Но и с учетом всего этого никогда нет стопроцентной уверенности в том, что некий двоичный файл записан в кодировке ASCII или UTF-8 просто потому, что в нем не встречаются определенные комбинации битов.

Если вы являетесь веб-разработчиком и часто имеете дело с WordPress то наверное не один раз сталкивались с кодировкой UTF-8. Например, любая тема, themeforest WoodMart не исключение, работает полностью с UTF-8.

Однако известно, что в естественных языках есть свои правила и ограничения. Поэтому если допустить, что поток байтов — это простой текст на естественном языке, то его кодировку можно попытаться определить с помощью различных эвристических правил и статистики.

Например, если часто встречается байт b’\x00′, то это, скорее всего, 16- или 32-разрядная кодировка, но не 8-разрядная схема, потому что нулевые байты в открытом тексте — очевидная ошибка.

Если часто встречается последовательность b’\x20\x00′, то это, наверное, символ пробела(U+0020) в кодировке UTF-16LE, а не малоизвестный символ U+2000 EN QUAD.

Именно так и работает пакет Chardet — универсальный детектор кодировки символов( https://pypi.python.org/pypi/chardet ) — который пытается распознать одну из 30 поддерживаемых кодировок.

Chardet — написанная на Python библиотека, которую вы можете включить в свою программу, а, кроме нее, пакет содержит также командную утилиту chardetect. Вот обычный пример запуска команды chardetect если дать ей имя файла как первый аргумент:

Как же определить кодировку последовательности байтов файла не из командной строки, а использовав модуль chardet?

Используйте следующий пример кода:

Хотя в самих двоичных последовательностях закодированного текста обычно нет явных указаний на кодировку, в некоторых UTF-форматах в начале файла может находиться маркер порядка байтов.

Работа с файлами в Python

В этой статье вы узнаете как организовать работать с файлами в Python 3.

Создайте файл files.py и копируйте туда код из примеров.

Запустить файл можно командой

Создать

Создать файл можно командой open

rb чтение в бинарном режиме

rt чтение в текстовом режиме

w только запись.

wb запись в бинарном режиме

wt запись в текстовом режиме

w+ запись и чтение

a запись в конец файла — сохранит данные, которые были в файле

b — это селектор бинарного режима

t — это селектор текстового режима

Любая опция с w перезапишет существующий файл — будьте внимательны!

f = open («log.txt»,»w+»)

Кодировка

import sys print (sys.getdefaultencoding())

Открыть файл

open ( path_to_file , mode , encoding )

По умолчанию используется кодировка utf-8

Чтобы открыть файл для чтения выполните

f = open («log.txt»,»r»)

Если файл log.txt не существует, он не будет создан

raceback (most recent call last): File «files.py», line 1, in <module> f = open('log.txt', 'r') FileNotFoundError: [Errno 2] No such file or directory: 'log.txt'

Закрыть файл

Чтобы закрыть файл выполните

Менеджер контекста

Предпочтительнее использовать менеджер контекста для работы с файлами

Как только вы выйдете из блока в котором открыт файл — он автоматически закроется

with open ('text.txt', 'r') as f: pass print (f.closed)

Будем рассматривать примеры работы с файлами как с использованием менеджера контекста так и без него.

read(): чтение файла

Получать данные из файла можно с помощью read()

В неё можно передавать аргумент типа int и тогда будет возвращено соответсвующее количество байт содераждания файла.

Прочитать содержимое файла

with open ('sites.txt', 'r') as f: f_contents = f.read() print (f_contents)

www.urn.su www.heihei.ru www.topbicycle.ru

Рассмотрим файл sites.md который состоит из одной строки

Чтобы получить всё что осталось в файл нужно вызвать read() без аргументов.

Если вызвать read() ещё раз, вернётся пустая строка

В данный момент указатель стоит на конце файла, но его можно переместить с помощью seek()

seek(0): перемещение в начало файла

С помощью seek(0) можно поставить указатель в начало файла.

Перейдём в конец файла sites.md

Теперь с помощью seek() поставим указатель в начало

Очистить файл

readline(): построчное чтение

Метод readline() выводит содержимое построчно.

А метод readlines() выводит все строки в виде списка

Все строки с символом перехода на новую строку — readlines

with open ('sites.txt', 'r') as f: f_contents = f.readlines() print (f_contents)

Строки по одной readline

with open ('sites.txt', 'r') as f: f_contents = f.readline() print (f_contents) f_contents = f.readline() print (f_contents)

Строки по одной без лишних переходов end=''

with open ('sites.txt', 'r') as f: f_contents = f.readline() print (f_contents, end = '') f_contents = f.readline() print (f_contents, end = '')

Цикл для построчного вывода

with open ('sites.txt', 'r') as f: for line in f: print (line, end = '')

www.urn.su www.heihei.ru www.topbicycle.ru

В качестве альтернативы можно использовать sys.stdout.write()

import sys f = open (sys.argv[ 1 ], mode= 'rt' , encoding= 'utf-8' ) for line in f: sys.stdout.write(line) f.close()

python files.py sites.txt

www.urn.su www.heihei.ru www.topbicycle.ru

Прочитать определённое количество символов

with open ('sites.txt', 'r') as f: f_contents = f.read(20) print (f_contents)

Если выполнять эту команду последовательно — будут прочитаны следующие символы

with open ('sites.txt', 'r') as f: f_contents = f.read(20) print (f_contents, end = '') f_contents = f.read(20) print (f_contents, end = '')

www.urn.su www.heihei.ru www.topbicycle.

Цикл для произвольного количества символов .read

with open ('sites.txt', 'r') as f: size_to_read = 10 f_contents = f.read(size_to_read) while len(f_contents) > 0: print (f_contents, end = '') f_contents = f.read(size_to_read)

www.urn.su www.heihei.ru www.topbicycle.ru

Выражение f_contents = f.read(size_to_read) нужно для того, чтобы когда файл закончится и f.read(size_to_read) станет нулем len(f_contents) тоже станет нулем и цикл завершится

Имя файла

Пример программы, которая выводит на экран имя файла и режим, в котором он открыт

f = open ('log.txt', 'r') print (f.name) print (f.mode) f.close()

Если файл log.txt существует, то в терминале вы увидите

Копирование файлов

Текстовые файлы

Их можно копировать построчно

with open ('sites.txt', 'r') as rf: with open ('sites_copy.txt', 'w') as wf: for line in rf: wf.write(line)

www.urn.su www.heihei.ru www.topbicycle.ru

Изображения

Их тоже можно копировать построчно, но открывать и записывать нужно в побитовом режиме. То есть нужно добавлять опцию b

Скачайте изображение велосипеда с сайта TopBicycle.ru или возьмите любую другую картинку

wget https://topbicycle.ru/b/img/stels_pilot_950_MD_26.jpg
ls

with open ('stels_pilot_950_MD_26.jpg', 'rb') as rf: with open ('stels_pilot_950_MD_26_copy.jpg', 'wb') as wf: for line in rf: wf.write(line)

python3 files.py
ls

Более правильным подходом считается копирование не в построчном режиме а частями с фиксированным размером

with open ('stels_pilot_950_MD_26.jpg', 'rb') as rf: with open ('stels_pilot_950_MD_26_copy.jpg', 'wb') as wf: chunk_size = 4096 rf_chunk = rf.read(chunk_size) while len(rf_chunk) > 0: wf.write(rf_chunk) rf_chunk = rf.read(chunk_size)

Записать файл

Чтобы очистить файл от старого содержимого и записать в него новое используется опция w (write)

with open ('log.txt', 'w') as f: f.write(«some text»)

13 и 9 это число байт переданное в файл

cat sites.md www.topbicycle.ru www.heihei.ru eth1.ruwww.aviasales.ru www.booking.comwww.tutu.ru www.velodrive.ruwww.velosklad.ru%

-rw-r—r— 1 andrei users 23 Mar 12 18:14 sites.md

Конечный размер файла будет зависеть от опецарионной системы.

В Windows и Linux разные переносы строк, поэтому когда Python применяет свой универсальный перенос строки количество байт может увеличится на 1 а может остаться прежним.

write() возвращает количество байт, переданных в файл, а не фактический размер записанных данных.

Дописать в файл

Если нужно добавить новые данные к предыдущему содержимому без удаления — используется опция a (append)

with open ('log.txt', 'a') as f: f.write(«some text»)

Рассмотрим пример добавления данных в файл sites.md с помощью метода writelines()

www.topbicycle.ru www.heihei.ru www.eth1.ru

www.topbicycle.ru www.heihei.ru eth1.ruwww.aviasales.ru www.booking.comwww.tutu.ru www.velodrive.ruwww.velosklad.ru

Видно, что переносы строк появились только там, где из указали вручную.

Записать json в файл

import json # нужно где-то взять json r = urllib.request.urlopen('http://urn.su/api/v1/getjson') rr = r.read() rj = json.loads(rr) with open ('file.txt', 'w') as f: json.dump(rj, f)

Удалить первые несколько строк файла

with open ('log.txt', 'a') as fin: data = fin.readlines()[1:] with open ('new.txt', 'w') as fout: fout.writelines(data)

Запись вывода программы в файл

Если вы запускаете скрипт из терминала, воспользуйтесь перенаправлением

python script.py > script.log

В самом скрипте можно временно подменить стандартный вывод.

Допустим я делаю запрос к API

import sys … # Сохраним ссылку на оригинальный stdout original_stdout = sys.stdout with open ( «log.txt» , «a» ) as f: sys.stdout = f print (resp.data) sys.stdout = original_stdout

Тоже самое, если приходит json и хочется записать его красиво

import sys import json … with open («log.txt», «a») as f: sys.stdout = f print (json.dumps(resp.data, indent=4)) sys.stdout = original_stdout

Последовательность Рекамана

import sys from itertools import count, islice def sequence (): """Generate Recaman's sequence.""" seen = set () a = 0 for n in count( 1 ): yield a seen.add(a) c = a — n if c < 0 or c in seen: c = a + n a = c def write_sequence (filename, num): """Write Recaman's sequence to a text file.""" f = open (filename, mode= 'wt' , encoding= 'utf-8' ) f.writelines( f " \n " for r in islice(sequence(), num + 1 )) f.close() if __name__ == '__main__' : write_sequence(filename=sys.argv[ 1 ], num= int (sys.argv[ 2 ]))

python recaman.py recaman.dat 1000
cat recaman.dat

1 3 6 2 7 … 2687 3685 2686 3686

"""Read and print an integer series.""" import sys def read_series (filename): f = open (filename, mode= 'rt' , encoding= 'utf-8' ) series = [] for line in f: a = int (line.strip()) series.append(a) f.close() return series def main (filename): series = read_series(filename) print (series) if __name__ == "__main__" : filename = sys.argv[ 1 ] main(filename)

python series.py recaman.dat

[0, 1, 3, 6, 2, 7 … 3684, 2687, 3685, 2686, 3686]

Если в файле будут неподходящие данные ошибка будет показана в Traceback, а до закрытия файла дело не дойдёт.

echo badidea >> recaman.dat
python series.py recaman.dat

Traceback (most recent call last): File "/home/andrei/series.py", line 21, in <module> main(filename) File "/home/andrei/series.py", line 15, in main series = read_series(filename) File "/home/andrei/series.py", line 8, in read_series a = int(line.strip()) ValueError: invalid literal for int() with base 10: 'badidea'

Это серьёзная проблема, и обычно решается использованием менеджера контекста , но можно решить и добавлением try , finally

Модифицируем функцию read_series() заодно добавив генератор списка

def read_series (filename): try : f = open (filename, mode= 'rt' , encoding= 'utf-8' ) return [ int (line.strip()) for line in f] finally : f.close()

С with получается короче.

def read_series (filename): with open (filename, mode= 'rt' , encoding= 'utf-8' ) as f: return [ int (line.strip()) for line in f]

В write_sequence() из recaman.py тоже лучше применить with

def write_sequence (filename, num): """Write Recaman's sequence to a text file.""" with open (filename, mode= 'wt' , encoding= 'utf-8' ) as f: f.writelines( f " \n " for r in islice(sequence(), num + 1 ))

Пример работы с bytes

"""A module for dealing with BMP bitmap image files.""" def write_grayscale (filename, pixels): """Creates and writes a grayscale BMP file. Args: filename: The name of the BMP file to be created. pixels: A rectangular image stored as a sequence of rows. Each row must be an iterable series of integers in the range 0-255. Raises: ValueError: If any of the integer values are out of range. OSError: If the file couldn't be written. """ height = len (pixels) width = len (pixels[ 0 ]) with open (filename, 'wb' ) as bmp: # BMP Header bmp.write(b 'BM' ) size_bookmark = bmp.tell() # The next four bytes hold the filesize as a 32-bit bmp.write(b ' \x00\x00\x00\x00 ' ) # little-endian integer. Zero placeholder for now. bmp.write(b ' \x00\x00 ' ) # Unused 16-bit integet — should be zero bmp.write(b ' \x00\x00 ' ) # Unused 16-bit integet — should be zero pixel_offset_bookmark = bmp.tell() # The next four bytes hold the integer offset to the bmp.write(b ' \x00\x00\x00\x00 ' ) # pixel data. Zero placeholder for now. # Image Header bmp.write(b ' \x28\x00\x00\x00 ' ) # Image header size in bytes — 40 decimal bmp.write(_int32_to_bytes(width)) # Image width in pixels bmp.write(_int32_to_bytes(height)) # Image height in pixels bmp.write(b ' \x01\x00 ' ) # Number of image planes bmp.write(b ' \x08\x00 ' ) # Bits per pixel 8 for grayscale bmp.write(b ' \x00\x00\x00\x00 ' ) # No compression bmp.write(b ' \x00\x00\x00\x00 ' ) # Zero for uncompressed images bmp.write(b ' \x00\x00\x00\x00 ' ) # Unused pixels per meter bmp.write(b ' \x00\x00\x00\x00 ' ) # Unused pixels per meter bmp.write(b ' \x00\x00\x00\x00 ' ) # Use whole color table bmp.write(b ' \x00\x00\x00\x00 ' ) # All colors are important # Color palette — a linear grayscale for c in range ( 256 ): bmp.write( bytes ((c, c, c, 0 ))) # Blue, Green, Red, Zero # Pixel data pixel_data_bookmark = bmp.tell() for row in reversed (pixels): # BMP files are bottom to top row_data = bytes (row) bmp.write(row_data) padding = b ' \x00 ' * (( 4 — ( len (row) % 4 )) % 4 ) # Pad row to multiple of four bytes bmp.write(padding) # End of file eof_bookmark = bmp.tell() # Fill in file size placeholder bmp.seek(size_bookmark) bmp.write(_int32_to_bytes(eof_bookmark)) # Fill in pixel offset placeholder bmp.seek(pixel_offset_bookmark) bmp.write(_int32_to_bytes(pixel_data_bookmark)) def _int32_to_bytes (i): """Convert an integer to four bytes in little-endian format.""" # &: Bitwise-and # >>: Right-shift return bytes ( (i & 0xff , i >> 8 & 0xff , i >> 16 & 0xff , i >> 24 & 0xff ) )

import math def mandel (real, imag): """The logarighm of number of iterations needed to determine whether a complex point is in the Mandelbrot set. Args: real: The real coordinate imag: The imaginary coordinate Returns: An integer in the range 1-255. """ x = 0 y = 0 for i in range ( 1 , 257 ): if x*x + y*y > 4.0 : break xt = real + x*x — y*y y = imag + 2.0 * x * y x = xt return int (math.log(i) * 256 / math.log( 256 )) — 1 def mandelbrot (size_x, size_y): """Make an Mandelbrot set image. Args: size_x: Image width size_y: Image height Returns: A list of lists of integers in the range 0-255 """ return [[mandel(( 3.5 * x / size_x) — 2.5 , ( 2.0 * y / size_y) — 1.0 ) for x in range (size_x)] for y in range (size_y)]

>>> import fractal >>> pixels = fractal.mandelbrot(448, 256) >>> import reprlib >>> reprlib.repr(pixels)

'[[31, 31, 31, 31, 31, 31, . ], [31, 31, 31, 31, 31, 31, . ], [31, 31, 31, 31, 31, 31, . ], [31, 31, 31, 31, 31, 31, . ], [31, 31, 31, 31, 31, 31, . ], [31, 31, 31, 31, 31, 31, . ], . ]'

>>> import bmp >>> bmp.write_grayscale("mandel.bmp", pixels)

Определение размеров bmp изображения

def dimensions (filename): """Determine the dimensions in pixels of a BMP image. Args: filename: The filename of a BMP file. Returns: A tuple containing two integers with the width and height in pixels. Raises: ValueError: If the file was not a BMP file. OSError: If there was a problem reading the file. """ with open (filename, 'rb' ) as f: magic = f.read( 2 ) if magic != b 'BM' : raise ValueError (f " is not a BMP file" ) f.seek( 18 ) width_bytes = f.read( 4 ) height_bytes = f.read( 4 ) return ( _bytes_to_int32(width_bytes), _bytes_to_int32(height_bytes)) def _bytes_to_int32 (b): "Convert a bytes object containing four bytes into an integer." return b[ 0 ] | (b[ 1 ] << 8 ) | (b[ 2 ] << 16 ) | (b[ 3 ] << 24 )

encode()

Преобразовать в «кириллический» iso-8859-5 не получится

>>> j.encode('iso-8859-5') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.8/encodings/iso8859_5.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_table) UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-1: character maps to <undefined>

j.encode('iso-8859-5') # это тоже что и j.encode('iso-8859-5', errors='strict')

Определить кодировки файлов

Пример скрипта для определения кодировок файлов. О том как создать файлы в разных кодировках в Linux читайте здесь

python -m pip install python-magic

import magic def get_encoding (sample): blob = open (sample, 'rb' ).read() m = magic.open(magic.MAGIC_MIME_ENCODING) m.load() encoding = m.buffer(blob) return encoding files = [ 'utf-8-file' , 'windows-1251-file' , 'shift-jis-file' ] for f in files: print (get_encoding(f))

utf-8 iso-8859-1 unknown-8bit

С определением SHIFT-JIS пока проблемы

Путь до файла

python -m pip install pathlib

import pathlib from pathlib import Path dir_path = pathlib.Path.cwd() print (dir_path)

Прочитать файл из другой директории

Предположим, что мы находимся в директории one проекта file_path:

file_path/ ├── one │ └── path.py └── two └── sites.txt

Прочитать файл sites.txt с помощью Python поможет библиотека pathlib

import pathlib from pathlib import Path dir_path = pathlib.Path.cwd() path = Path(dir_path, ".." , "two" , "sites.txt" ) with open (path, "r" ) as f: sites = f.read() print (sites)

Подпишитесь на Telegram канал @aofeed чтобы следить за выходом новых статей и обновлением старых

How to determine the encoding of text

I received some text that is encoded, but I don’t know what charset was used. Is there a way to determine the encoding of a text file using Python? How can I detect the encoding/codepage of a text file deals with C#.

Trenton McKinney's user avatar

16 Answers 16

EDIT: chardet seems to be unmantained but most of the answer applies. Check https://pypi.org/project/charset-normalizer/ for an alternative

Correctly detecting the encoding all times is impossible.

(From chardet FAQ:)

However, some encodings are optimized for specific languages, and languages are not random. Some character sequences pop up all the time, while other sequences make no sense. A person fluent in English who opens a newspaper and finds “txzqJv 2!dasd0a QqdKjvz” will instantly recognize that that isn’t English (even though it is composed entirely of English letters). By studying lots of “typical” text, a computer algorithm can simulate this kind of fluency and make an educated guess about a text’s language.

There is the chardet library that uses that study to try to detect encoding. chardet is a port of the auto-detection code in Mozilla.

You can also use UnicodeDammit. It will try the following methods:

  • An encoding discovered in the document itself: for instance, in an XML declaration or (for HTML documents) an http-equiv META tag. If Beautiful Soup finds this kind of encoding within the document, it parses the document again from the beginning and gives the new encoding a try. The only exception is if you explicitly specified an encoding, and that encoding actually worked: then it will ignore any encoding it finds in the document.
  • An encoding sniffed by looking at the first few bytes of the file. If an encoding is detected at this stage, it will be one of the UTF-* encodings, EBCDIC, or ASCII.
  • An encoding sniffed by the chardet library, if you have it installed.
  • UTF-8
  • Windows-1252

Another option for working out the encoding is to use libmagic (which is the code behind the file command). There are a profusion of python bindings available.

The python bindings that live in the file source tree are available as the python-magic (or python3-magic) debian package. It can determine the encoding of a file by doing:

There is an identically named, but incompatible, python-magic pip package on pypi that also uses libmagic . It can also get the encoding, by doing:

Some encoding strategies, please uncomment to taste :

You might like to check the encoding by opening and reading the file in a form of a loop. but you might need to check the filesize first :

zzart's user avatar

Here is an example of reading and taking at face value a chardet encoding prediction, reading n_lines from the file in the event it is large.

chardet also gives you a probability (i.e. confidence ) of it’s encoding prediction (haven’t looked how they come up with that), which is returned with its prediction from chardet.predict() , so you could work that in somehow if you like.

This might be helpful

If you are not satisfied with the automatic tools you can try all codecs and see which codec is right manually.

This script creates at least 9409 lines of output. So, if the output cannot fit to the terminal screen try to write the output to a text file.

rebahozkoc's user avatar

Bimo's user avatar

It is, in principle, impossible to determine the encoding of a text file, in the general case. So no, there is no standard Python library to do that for you.

If you have more specific knowledge about the text file (e.g. that it is XML), there might be library functions.

Depending on your platform, I just opt to use the linux shell file command. This works for me since I am using it in a script that exclusively runs on one of our linux machines.

Obviously this isn’t an ideal solution or answer, but it could be modified to fit your needs. In my case I just need to determine whether a file is UTF-8 or not.

If you know the some content of the file you can try to decode it with several encoding and see which is missing. In general there is no way since a text file is a text file and those are stupid 😉

This site has python code for recognizing ascii, encoding with boms, and utf8 no bom: https://unicodebook.readthedocs.io/guess_encoding.html. Read file into byte array (data): http://www.codecodex.com/wiki/Read_a_file_into_a_byte_array. Here’s an example. I’m in osx.

Using linux file -i command

Emeeus's user avatar

You can use `python-magic package which does not load the whole file to memory:

The output is the encoding name for example:

  • iso-8859-1
  • us-ascii
  • utf-8

Alon Barad's user avatar

You can use the chardet module

Or you can use the chardet3 command in linux but it takes a few time :

djamel lardjani's user avatar

Some text files are aware of their encoding, most are not. Aware:

  • a text file having a BOM
  • an XML file is encoded in UTF-8 or its encoding is given in the preamble
  • a JSON file is always encoded in UTF-8
  • a CSV file
  • any random text file

Some encodings are versatile, ie they can decode any sequence of bytes, some are not. US-ASCII is not versatile, since any byte greater than 127 is not mapped to any character. UTF-8 is not versatile since any sequence of bytes is not valid.

On the contrary, Latin-1, Windows-1252, etc. are versatile (even if some bytes are not officially mapped to a character):

Given a random text file encoded in a sequence of bytes, you can’t determine the encoding unless the file is aware of its encoding, because some encodings are versatile. But you can sometimes exclude non versatile encodings. All versatile encodings are still possible. The chardet modules uses the frequency of bytes to guess which encoding fits the best to the encoded text.

If you don’t want to use this module or a similar one, here’s a simple method:

  • check if the file is aware of its encoding (BOM)
  • check non versatile encodings and accept the first that can decode the bytes (ASCII before UTF-8 because it is stricter)
  • choose a fallback encoding.

The second step is a bit risky if you check only a sample, because some bytes in the rest of the file may be invalid.

Remember that non versatile encoding may fail. The errors parameter of the decode method can be set to ‘ignore’ , ‘replace’ or ‘backslashreplace’ to avoid exceptions.

codecs — Codec registry and base classes¶

This module defines base classes for standard Python codecs (encoders and decoders) and provides access to the internal Python codec registry, which manages the codec and error handling lookup process. Most standard codecs are text encodings , which encode text to bytes (and decode bytes to text), but there are also codecs provided that encode text to text, and bytes to bytes. Custom codecs may encode and decode between arbitrary types, but some module features are restricted to be used specifically with text encodings or with codecs that encode to bytes .

The module defines the following functions for encoding and decoding with any codec:

codecs. encode ( obj , encoding = ‘utf-8’ , errors = ‘strict’ ) ¶

Encodes obj using the codec registered for encoding.

Errors may be given to set the desired error handling scheme. The default error handler is ‘strict’ meaning that encoding errors raise ValueError (or a more codec specific subclass, such as UnicodeEncodeError ). Refer to Codec Base Classes for more information on codec error handling.

codecs. decode ( obj , encoding = ‘utf-8’ , errors = ‘strict’ ) ¶

Decodes obj using the codec registered for encoding.

Errors may be given to set the desired error handling scheme. The default error handler is ‘strict’ meaning that decoding errors raise ValueError (or a more codec specific subclass, such as UnicodeDecodeError ). Refer to Codec Base Classes for more information on codec error handling.

The full details for each codec can also be looked up directly:

codecs. lookup ( encoding ) ¶

Looks up the codec info in the Python codec registry and returns a CodecInfo object as defined below.

Encodings are first looked up in the registry’s cache. If not found, the list of registered search functions is scanned. If no CodecInfo object is found, a LookupError is raised. Otherwise, the CodecInfo object is stored in the cache and returned to the caller.

class codecs. CodecInfo ( encode , decode , streamreader = None , streamwriter = None , incrementalencoder = None , incrementaldecoder = None , name = None ) ¶

Codec details when looking up the codec registry. The constructor arguments are stored in attributes of the same name:

The name of the encoding.

The stateless encoding and decoding functions. These must be functions or methods which have the same interface as the encode() and decode() methods of Codec instances (see Codec Interface ). The functions or methods are expected to work in a stateless mode.

Incremental encoder and decoder classes or factory functions. These have to provide the interface defined by the base classes IncrementalEncoder and IncrementalDecoder , respectively. Incremental codecs can maintain state.

Stream writer and reader classes or factory functions. These have to provide the interface defined by the base classes StreamWriter and StreamReader , respectively. Stream codecs can maintain state.

To simplify access to the various codec components, the module provides these additional functions which use lookup() for the codec lookup:

codecs. getencoder ( encoding ) ¶

Look up the codec for the given encoding and return its encoder function.

Raises a LookupError in case the encoding cannot be found.

codecs. getdecoder ( encoding ) ¶

Look up the codec for the given encoding and return its decoder function.

Raises a LookupError in case the encoding cannot be found.

codecs. getincrementalencoder ( encoding ) ¶

Look up the codec for the given encoding and return its incremental encoder class or factory function.

Raises a LookupError in case the encoding cannot be found or the codec doesn’t support an incremental encoder.

codecs. getincrementaldecoder ( encoding ) ¶

Look up the codec for the given encoding and return its incremental decoder class or factory function.

Raises a LookupError in case the encoding cannot be found or the codec doesn’t support an incremental decoder.

codecs. getreader ( encoding ) ¶

Look up the codec for the given encoding and return its StreamReader class or factory function.

Raises a LookupError in case the encoding cannot be found.

codecs. getwriter ( encoding ) ¶

Look up the codec for the given encoding and return its StreamWriter class or factory function.

Raises a LookupError in case the encoding cannot be found.

Custom codecs are made available by registering a suitable codec search function:

codecs. register ( search_function ) ¶

Register a codec search function. Search functions are expected to take one argument, being the encoding name in all lower case letters with hyphens and spaces converted to underscores, and return a CodecInfo object. In case a search function cannot find a given encoding, it should return None .

Читать:
Как разобрать 3д объект в иллюстраторе

Changed in version 3.9: Hyphens and spaces are converted to underscore.

Unregister a codec search function and clear the registry’s cache. If the search function is not registered, do nothing.

New in version 3.10.

While the builtin open() and the associated io module are the recommended approach for working with encoded text files, this module provides additional utility functions and classes that allow the use of a wider range of codecs when working with binary files:

codecs. open ( filename , mode = ‘r’ , encoding = None , errors = ‘strict’ , buffering = — 1 ) ¶

Open an encoded file using the given mode and return an instance of StreamReaderWriter , providing transparent encoding/decoding. The default file mode is ‘r’ , meaning to open the file in read mode.

If encoding is not None , then the underlying encoded files are always opened in binary mode. No automatic conversion of ‘\n’ is done on reading and writing. The mode argument may be any binary mode acceptable to the built-in open() function; the ‘b’ is automatically added.

encoding specifies the encoding which is to be used for the file. Any encoding that encodes to and decodes from bytes is allowed, and the data types supported by the file methods depend on the codec used.

errors may be given to define the error handling. It defaults to ‘strict’ which causes a ValueError to be raised in case an encoding error occurs.

buffering has the same meaning as for the built-in open() function. It defaults to -1 which means that the default buffer size will be used.

Changed in version 3.11: The ‘U’ mode has been removed.

Return a StreamRecoder instance, a wrapped version of file which provides transparent transcoding. The original file is closed when the wrapped version is closed.

Data written to the wrapped file is decoded according to the given data_encoding and then written to the original file as bytes using file_encoding. Bytes read from the original file are decoded according to file_encoding, and the result is encoded using data_encoding.

If file_encoding is not given, it defaults to data_encoding.

errors may be given to define the error handling. It defaults to ‘strict’ , which causes ValueError to be raised in case an encoding error occurs.

codecs. iterencode ( iterator , encoding , errors = ‘strict’ , ** kwargs ) ¶

Uses an incremental encoder to iteratively encode the input provided by iterator. This function is a generator . The errors argument (as well as any other keyword argument) is passed through to the incremental encoder.

This function requires that the codec accept text str objects to encode. Therefore it does not support bytes-to-bytes encoders such as base64_codec .

codecs. iterdecode ( iterator , encoding , errors = ‘strict’ , ** kwargs ) ¶

Uses an incremental decoder to iteratively decode the input provided by iterator. This function is a generator . The errors argument (as well as any other keyword argument) is passed through to the incremental decoder.

This function requires that the codec accept bytes objects to decode. Therefore it does not support text-to-text encoders such as rot_13 , although rot_13 may be used equivalently with iterencode() .

The module also provides the following constants which are useful for reading and writing to platform dependent files:

codecs. BOM ¶ codecs. BOM_BE ¶ codecs. BOM_LE ¶ codecs. BOM_UTF8 ¶ codecs. BOM_UTF16 ¶ codecs. BOM_UTF16_BE ¶ codecs. BOM_UTF16_LE ¶ codecs. BOM_UTF32 ¶ codecs. BOM_UTF32_BE ¶ codecs. BOM_UTF32_LE ¶

These constants define various byte sequences, being Unicode byte order marks (BOMs) for several encodings. They are used in UTF-16 and UTF-32 data streams to indicate the byte order used, and in UTF-8 as a Unicode signature. BOM_UTF16 is either BOM_UTF16_BE or BOM_UTF16_LE depending on the platform’s native byte order, BOM is an alias for BOM_UTF16 , BOM_LE for BOM_UTF16_LE and BOM_BE for BOM_UTF16_BE . The others represent the BOM in UTF-8 and UTF-32 encodings.

Codec Base Classes¶

The codecs module defines a set of base classes which define the interfaces for working with codec objects, and can also be used as the basis for custom codec implementations.

Each codec has to define four interfaces to make it usable as codec in Python: stateless encoder, stateless decoder, stream reader and stream writer. The stream reader and writers typically reuse the stateless encoder/decoder to implement the file protocols. Codec authors also need to define how the codec will handle encoding and decoding errors.

Error Handlers¶

To simplify and standardize error handling, codecs may implement different error handling schemes by accepting the errors string argument:

The following error handlers can be used with all Python Standard Encodings codecs:

Raise UnicodeError (or a subclass), this is the default. Implemented in strict_errors() .

Ignore the malformed data and continue without further notice. Implemented in ignore_errors() .

Replace with a replacement marker. On encoding, use ? (ASCII character). On decoding, use � (U+FFFD, the official REPLACEMENT CHARACTER). Implemented in replace_errors() .

Replace with backslashed escape sequences. On encoding, use hexadecimal form of Unicode code point with formats \xhh \uxxxx \Uxxxxxxxx . On decoding, use hexadecimal form of byte value with format \xhh . Implemented in backslashreplace_errors() .

On decoding, replace byte with individual surrogate code ranging from U+DC80 to U+DCFF . This code will then be turned back into the same byte when the ‘surrogateescape’ error handler is used when encoding the data. (See PEP 383 for more.)

The following error handlers are only applicable to encoding (within text encodings ):

Replace with XML/HTML numeric character reference, which is a decimal form of Unicode code point with format &#num; Implemented in xmlcharrefreplace_errors() .

Replace with \N <. >escape sequences, what appears in the braces is the Name property from Unicode Character Database. Implemented in namereplace_errors() .

In addition, the following error handler is specific to the given codecs:

utf-8, utf-16, utf-32, utf-16-be, utf-16-le, utf-32-be, utf-32-le

Allow encoding and decoding surrogate code point ( U+D800 — U+DFFF ) as normal code point. Otherwise these codecs treat the presence of surrogate code point in str as an error.

New in version 3.1: The ‘surrogateescape’ and ‘surrogatepass’ error handlers.

Changed in version 3.4: The ‘surrogatepass’ error handler now works with utf-16* and utf-32* codecs.

New in version 3.5: The ‘namereplace’ error handler.

Changed in version 3.5: The ‘backslashreplace’ error handler now works with decoding and translating.

The set of allowed values can be extended by registering a new named error handler:

codecs. register_error ( name , error_handler ) ¶

Register the error handling function error_handler under the name name. The error_handler argument will be called during encoding and decoding in case of an error, when name is specified as the errors parameter.

For encoding, error_handler will be called with a UnicodeEncodeError instance, which contains information about the location of the error. The error handler must either raise this or a different exception, or return a tuple with a replacement for the unencodable part of the input and a position where encoding should continue. The replacement may be either str or bytes . If the replacement is bytes, the encoder will simply copy them into the output buffer. If the replacement is a string, the encoder will encode the replacement. Encoding continues on original input at the specified position. Negative position values will be treated as being relative to the end of the input string. If the resulting position is out of bound an IndexError will be raised.

Decoding and translating works similarly, except UnicodeDecodeError or UnicodeTranslateError will be passed to the handler and that the replacement from the error handler will be put into the output directly.

Previously registered error handlers (including the standard error handlers) can be looked up by name:

codecs. lookup_error ( name ) ¶

Return the error handler previously registered under the name name.

Raises a LookupError in case the handler cannot be found.

The following standard error handlers are also made available as module level functions:

codecs. strict_errors ( exception ) ¶

Implements the ‘strict’ error handling.

Each encoding or decoding error raises a UnicodeError .

codecs. ignore_errors ( exception ) ¶

Implements the ‘ignore’ error handling.

Malformed data is ignored; encoding or decoding is continued without further notice.

codecs. replace_errors ( exception ) ¶

Implements the ‘replace’ error handling.

Substitutes ? (ASCII character) for encoding errors or � (U+FFFD, the official REPLACEMENT CHARACTER) for decoding errors.

codecs. backslashreplace_errors ( exception ) ¶

Implements the ‘backslashreplace’ error handling.

Malformed data is replaced by a backslashed escape sequence. On encoding, use the hexadecimal form of Unicode code point with formats \xhh \uxxxx \Uxxxxxxxx . On decoding, use the hexadecimal form of byte value with format \xhh .

Changed in version 3.5: Works with decoding and translating.

Implements the ‘xmlcharrefreplace’ error handling (for encoding within text encoding only).

The unencodable character is replaced by an appropriate XML/HTML numeric character reference, which is a decimal form of Unicode code point with format &#num; .

codecs. namereplace_errors ( exception ) ¶

Implements the ‘namereplace’ error handling (for encoding within text encoding only).

The unencodable character is replaced by a \N <. >escape sequence. The set of characters that appear in the braces is the Name property from Unicode Character Database. For example, the German lowercase letter ‘ß’ will be converted to byte sequence \N .

New in version 3.5.

Stateless Encoding and Decoding¶

The base Codec class defines these methods which also define the function interfaces of the stateless encoder and decoder:

Codec. encode ( input , errors = ‘strict’ ) ¶

Encodes the object input and returns a tuple (output object, length consumed). For instance, text encoding converts a string object to a bytes object using a particular character set encoding (e.g., cp1252 or iso-8859-1 ).

The errors argument defines the error handling to apply. It defaults to ‘strict’ handling.

The method may not store state in the Codec instance. Use StreamWriter for codecs which have to keep state in order to make encoding efficient.

The encoder must be able to handle zero length input and return an empty object of the output object type in this situation.

Codec. decode ( input , errors = ‘strict’ ) ¶

Decodes the object input and returns a tuple (output object, length consumed). For instance, for a text encoding , decoding converts a bytes object encoded using a particular character set encoding to a string object.

For text encodings and bytes-to-bytes codecs, input must be a bytes object or one which provides the read-only buffer interface – for example, buffer objects and memory mapped files.

The errors argument defines the error handling to apply. It defaults to ‘strict’ handling.

The method may not store state in the Codec instance. Use StreamReader for codecs which have to keep state in order to make decoding efficient.

The decoder must be able to handle zero length input and return an empty object of the output object type in this situation.

Incremental Encoding and Decoding¶

The IncrementalEncoder and IncrementalDecoder classes provide the basic interface for incremental encoding and decoding. Encoding/decoding the input isn’t done with one call to the stateless encoder/decoder function, but with multiple calls to the encode() / decode() method of the incremental encoder/decoder. The incremental encoder/decoder keeps track of the encoding/decoding process during method calls.

The joined output of calls to the encode() / decode() method is the same as if all the single inputs were joined into one, and this input was encoded/decoded with the stateless encoder/decoder.

IncrementalEncoder Objects¶

The IncrementalEncoder class is used for encoding an input in multiple steps. It defines the following methods which every incremental encoder must define in order to be compatible with the Python codec registry.

class codecs. IncrementalEncoder ( errors = ‘strict’ ) ¶

Constructor for an IncrementalEncoder instance.

All incremental encoders must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.

The IncrementalEncoder may implement different error handling schemes by providing the errors keyword argument. See Error Handlers for possible values.

The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the IncrementalEncoder object.

encode ( object , final = False ) ¶

Encodes object (taking the current state of the encoder into account) and returns the resulting encoded object. If this is the last call to encode() final must be true (the default is false).

Reset the encoder to the initial state. The output is discarded: call .encode(object, final=True) , passing an empty byte or text string if necessary, to reset the encoder and to get the output.

Return the current state of the encoder which must be an integer. The implementation should make sure that 0 is the most common state. (States that are more complicated than integers can be converted into an integer by marshaling/pickling the state and encoding the bytes of the resulting string into an integer.)

Set the state of the encoder to state. state must be an encoder state returned by getstate() .

IncrementalDecoder Objects¶

The IncrementalDecoder class is used for decoding an input in multiple steps. It defines the following methods which every incremental decoder must define in order to be compatible with the Python codec registry.

class codecs. IncrementalDecoder ( errors = ‘strict’ ) ¶

Constructor for an IncrementalDecoder instance.

All incremental decoders must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.

The IncrementalDecoder may implement different error handling schemes by providing the errors keyword argument. See Error Handlers for possible values.

The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the IncrementalDecoder object.

decode ( object , final = False ) ¶

Decodes object (taking the current state of the decoder into account) and returns the resulting decoded object. If this is the last call to decode() final must be true (the default is false). If final is true the decoder must decode the input completely and must flush all buffers. If this isn’t possible (e.g. because of incomplete byte sequences at the end of the input) it must initiate error handling just like in the stateless case (which might raise an exception).

Reset the decoder to the initial state.

Return the current state of the decoder. This must be a tuple with two items, the first must be the buffer containing the still undecoded input. The second must be an integer and can be additional state info. (The implementation should make sure that 0 is the most common additional state info.) If this additional state info is 0 it must be possible to set the decoder to the state which has no input buffered and 0 as the additional state info, so that feeding the previously buffered input to the decoder returns it to the previous state without producing any output. (Additional state info that is more complicated than integers can be converted into an integer by marshaling/pickling the info and encoding the bytes of the resulting string into an integer.)

Set the state of the decoder to state. state must be a decoder state returned by getstate() .

Stream Encoding and Decoding¶

The StreamWriter and StreamReader classes provide generic working interfaces which can be used to implement new encoding submodules very easily. See encodings.utf_8 for an example of how this is done.

StreamWriter Objects¶

The StreamWriter class is a subclass of Codec and defines the following methods which every stream writer must define in order to be compatible with the Python codec registry.

class codecs. StreamWriter ( stream , errors = ‘strict’ ) ¶

Constructor for a StreamWriter instance.

All stream writers must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.

The stream argument must be a file-like object open for writing text or binary data, as appropriate for the specific codec.

The StreamWriter may implement different error handling schemes by providing the errors keyword argument. See Error Handlers for the standard error handlers the underlying stream codec may support.

The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the StreamWriter object.

Writes the object’s contents encoded to the stream.

Writes the concatenated iterable of strings to the stream (possibly by reusing the write() method). Infinite or very large iterables are not supported. The standard bytes-to-bytes codecs do not support this method.

Resets the codec buffers used for keeping internal state.

Calling this method should ensure that the data on the output is put into a clean state that allows appending of new fresh data without having to rescan the whole stream to recover state.

In addition to the above methods, the StreamWriter must also inherit all other methods and attributes from the underlying stream.

StreamReader Objects¶

The StreamReader class is a subclass of Codec and defines the following methods which every stream reader must define in order to be compatible with the Python codec registry.

class codecs. StreamReader ( stream , errors = ‘strict’ ) ¶

Constructor for a StreamReader instance.

All stream readers must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.

The stream argument must be a file-like object open for reading text or binary data, as appropriate for the specific codec.

The StreamReader may implement different error handling schemes by providing the errors keyword argument. See Error Handlers for the standard error handlers the underlying stream codec may support.

The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the StreamReader object.

The set of allowed values for the errors argument can be extended with register_error() .

read ( size = — 1 , chars = — 1 , firstline = False ) ¶

Decodes data from the stream and returns the resulting object.

The chars argument indicates the number of decoded code points or bytes to return. The read() method will never return more data than requested, but it might return less, if there is not enough available.

The size argument indicates the approximate maximum number of encoded bytes or code points to read for decoding. The decoder can modify this setting as appropriate. The default value -1 indicates to read and decode as much as possible. This parameter is intended to prevent having to decode huge files in one step.

The firstline flag indicates that it would be sufficient to only return the first line, if there are decoding errors on later lines.

The method should use a greedy read strategy meaning that it should read as much data as is allowed within the definition of the encoding and the given size, e.g. if optional encoding endings or state markers are available on the stream, these should be read too.

readline ( size = None , keepends = True ) ¶

Read one line from the input stream and return the decoded data.

size, if given, is passed as size argument to the stream’s read() method.

If keepends is false line-endings will be stripped from the lines returned.

readlines ( sizehint = None , keepends = True ) ¶

Read all lines available on the input stream and return them as a list of lines.

Line-endings are implemented using the codec’s decode() method and are included in the list entries if keepends is true.

sizehint, if given, is passed as the size argument to the stream’s read() method.

Resets the codec buffers used for keeping internal state.

Note that no stream repositioning should take place. This method is primarily intended to be able to recover from decoding errors.

In addition to the above methods, the StreamReader must also inherit all other methods and attributes from the underlying stream.

StreamReaderWriter Objects¶

The StreamReaderWriter is a convenience class that allows wrapping streams which work in both read and write modes.

The design is such that one can use the factory functions returned by the lookup() function to construct the instance.

class codecs. StreamReaderWriter ( stream , Reader , Writer , errors = ‘strict’ ) ¶

Creates a StreamReaderWriter instance. stream must be a file-like object. Reader and Writer must be factory functions or classes providing the StreamReader and StreamWriter interface resp. Error handling is done in the same way as defined for the stream readers and writers.

StreamReaderWriter instances define the combined interfaces of StreamReader and StreamWriter classes. They inherit all other methods and attributes from the underlying stream.

StreamRecoder Objects¶

The StreamRecoder translates data from one encoding to another, which is sometimes useful when dealing with different encoding environments.

The design is such that one can use the factory functions returned by the lookup() function to construct the instance.

class codecs. StreamRecoder ( stream , encode , decode , Reader , Writer , errors = ‘strict’ ) ¶

Creates a StreamRecoder instance which implements a two-way conversion: encode and decode work on the frontend — the data visible to code calling read() and write() , while Reader and Writer work on the backend — the data in stream.

You can use these objects to do transparent transcodings, e.g., from Latin-1 to UTF-8 and back.

The stream argument must be a file-like object.

The encode and decode arguments must adhere to the Codec interface. Reader and Writer must be factory functions or classes providing objects of the StreamReader and StreamWriter interface respectively.

Error handling is done in the same way as defined for the stream readers and writers.

StreamRecoder instances define the combined interfaces of StreamReader and StreamWriter classes. They inherit all other methods and attributes from the underlying stream.

Encodings and Unicode¶

Strings are stored internally as sequences of code points in range U+0000 – U+10FFFF . (See PEP 393 for more details about the implementation.) Once a string object is used outside of CPU and memory, endianness and how these arrays are stored as bytes become an issue. As with other codecs, serialising a string into a sequence of bytes is known as encoding, and recreating the string from the sequence of bytes is known as decoding. There are a variety of different text serialisation codecs, which are collectivity referred to as text encodings .

The simplest text encoding (called ‘latin-1’ or ‘iso-8859-1’ ) maps the code points 0–255 to the bytes 0x0 – 0xff , which means that a string object that contains code points above U+00FF can’t be encoded with this codec. Doing so will raise a UnicodeEncodeError that looks like the following (although the details of the error message may differ): UnicodeEncodeError: ‘latin-1’ codec can’t encode character ‘\u1234’ in position 3: ordinal not in range(256) .

There’s another group of encodings (the so called charmap encodings) that choose a different subset of all Unicode code points and how these code points are mapped to the bytes 0x0 – 0xff . To see how this is done simply open e.g. encodings/cp1252.py (which is an encoding that is used primarily on Windows). There’s a string constant with 256 characters that shows you which character is mapped to which byte value.

All of these encodings can only encode 256 of the 1114112 code points defined in Unicode. A simple and straightforward way that can store each Unicode code point, is to store each code point as four consecutive bytes. There are two possibilities: store the bytes in big endian or in little endian order. These two encodings are called UTF-32-BE and UTF-32-LE respectively. Their disadvantage is that if e.g. you use UTF-32-BE on a little endian machine you will always have to swap bytes on encoding and decoding. UTF-32 avoids this problem: bytes will always be in natural endianness. When these bytes are read by a CPU with a different endianness, then bytes have to be swapped though. To be able to detect the endianness of a UTF-16 or UTF-32 byte sequence, there’s the so called BOM (“Byte Order Mark”). This is the Unicode character U+FEFF . This character can be prepended to every UTF-16 or UTF-32 byte sequence. The byte swapped version of this character ( 0xFFFE ) is an illegal character that may not appear in a Unicode text. So when the first character in a UTF-16 or UTF-32 byte sequence appears to be a U+FFFE the bytes have to be swapped on decoding. Unfortunately the character U+FEFF had a second purpose as a ZERO WIDTH NO-BREAK SPACE : a character that has no width and doesn’t allow a word to be split. It can e.g. be used to give hints to a ligature algorithm. With Unicode 4.0 using U+FEFF as a ZERO WIDTH NO-BREAK SPACE has been deprecated (with U+2060 ( WORD JOINER ) assuming this role). Nevertheless Unicode software still must be able to handle U+FEFF in both roles: as a BOM it’s a device to determine the storage layout of the encoded bytes, and vanishes once the byte sequence has been decoded into a string; as a ZERO WIDTH NO-BREAK SPACE it’s a normal character that will be decoded like any other.

There’s another encoding that is able to encode the full range of Unicode characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two parts: marker bits (the most significant bits) and payload bits. The marker bits are a sequence of zero to four 1 bits followed by a 0 bit. Unicode characters are encoded like this (with x being payload bits, which when concatenated give the Unicode character):

Похожие статьи