Python unicodedecodeerror invalid start bytes

ошибка UnicodeDecodeError: кодек «utf-8» не может декодировать байт 0xff в позиции 0: недопустимый начальный байт

Python пытается преобразовать байтовый массив (a bytes , который предполагается, что он является строкой, кодированной utf-8), в строку unicode ( str ). Этот процесс, конечно, является расшифровкой в ​​соответствии с правилами utf-8. Когда он пытается это сделать, он встречает последовательность байтов, которая не допускается в строках, закодированных в utf-8 (а именно, это 0xff в позиции 0). Поскольку вы не указали какой-либо код, на который мы могли бы обратить внимание, мы можем только догадываться об остальном. Из трассировки стека можно предположить, что инициирующим действием было чтение из файла ( contents = open(path).read() ). Я предлагаю перекодировать это так:

with open(path, 'rb') as f: contents = f.read() 

То, что b в спецификаторе режима в open() указывает, что файл должен рассматриваться как двоичный, поэтому contents останется bytes . Никакая попытка декодирования не будет таким образом.

Я получаю сообщение об ошибке «ValueError: строка режима должна начинаться с« r »,« w »,« a »или« U », а не« br »»

@Unnikrishnan Хорошо, тогда используйте rb (я думал, что порядок не имеет значения, но, кажется, по крайней мере, в некоторых системах / версиях). Я изменил свой ответ соответственно.

byte 0xff in position 0 также может означать, что файл закодирован в UTF-16, тогда вы можете сделать with open(path, encoding=’utf-16′) as f: вместо

Используйте это решение, оно удалит (проигнорирует) символы и вернет строку без них. Используйте это только если вам нужно раздеть их, а не конвертировать.

with open(path, encoding="utf8", errors='ignore') as f: 

Используя errors=’ignore’ вы просто потеряете несколько символов. но если вы не заботитесь о них, так как они кажутся лишними символами, происходящими из-за неправильного форматирования и программирования клиентов, подключающихся к моему серверу сокетов. Тогда это простое прямое решение. ссылка

Работает и для decode (): contents = contents.decode(‘utf-8’, ‘ignore’) Источник: docs.python.org/3/howto/unicode.html#the-string-type

Источник

Ошибки при конвертации#

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

Например, кодировка ASCII не может преобразовать в байты кириллицу:

In [32]: hi_unicode = 'привет' In [33]: hi_unicode.encode('ascii') --------------------------------------------------------------------------- UnicodeEncodeError Traceback (most recent call last) ipython-input-33-ec69c9fd2dae> in module>() ----> 1 hi_unicode.encode('ascii') UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128) 

Аналогично, если строка «привет» преобразована в байты, и попробовать преобразовать ее в строку с помощью ascii, тоже получим ошибку:

In [34]: hi_unicode = 'привет' In [35]: hi_bytes = hi_unicode.encode('utf-8') In [36]: hi_bytes.decode('ascii') --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) ipython-input-36-aa0ada5e44e9> in module>() ----> 1 hi_bytes.decode('ascii') UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128) 

Еще один вариант ошибки, когда используются разные кодировки для преобразований:

In [37]: de_hi_unicode = 'grüezi' In [38]: utf_16 = de_hi_unicode.encode('utf-16') In [39]: utf_16.decode('utf-8') --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) ipython-input-39-4b4c731e69e4> in module>() ----> 1 utf_16.decode('utf-8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte 

Наличие ошибок — это хорошо. Они явно говорят, в чем проблема. Хуже, когда получается так:

In [40]: hi_unicode = 'привет' In [41]: hi_bytes = hi_unicode.encode('utf-8') In [42]: hi_bytes Out[42]: b'\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82' In [43]: hi_bytes.decode('utf-16') Out[43]: '뿐胑룐닐뗐苑' 

Обработка ошибок#

У методов encode и decode есть режимы обработки ошибок, которые указывают, как реагировать на ошибку преобразования.

Параметр errors в encode#

По умолчанию encode использует режим strict — при возникновении ошибок кодировки генерируется исключение UnicodeError. Примеры такого поведения были выше.

Вместо этого режима можно использовать replace, чтобы заменить символ знаком вопроса:

In [44]: de_hi_unicode = 'grüezi' In [45]: de_hi_unicode.encode('ascii', 'replace') Out[45]: b'gr?ezi' 

Или namereplace, чтобы заменить символ именем:

In [46]: de_hi_unicode = 'grüezi' In [47]: de_hi_unicode.encode('ascii', 'namereplace') Out[47]: b'gr\\Nezi' 

Кроме того, можно полностью игнорировать символы, которые нельзя закодировать:

In [48]: de_hi_unicode = 'grüezi' In [49]: de_hi_unicode.encode('ascii', 'ignore') Out[49]: b'grezi' 

Параметр errors в decode#

В методе decode по умолчанию тоже используется режим strict и генерируется исключение UnicodeDecodeError.

Если изменить режим на ignore, как и в encode, символы будут просто игнорироваться:

In [50]: de_hi_unicode = 'grüezi' In [51]: de_hi_utf8 = de_hi_unicode.encode('utf-8') In [52]: de_hi_utf8 Out[52]: b'gr\xc3\xbcezi' In [53]: de_hi_utf8.decode('ascii', 'ignore') Out[53]: 'grezi' 

Режим replace заменит символы:

In [54]: de_hi_unicode = 'grüezi' In [55]: de_hi_utf8 = de_hi_unicode.encode('utf-8') In [56]: de_hi_utf8.decode('ascii', 'replace') Out[56]: 'gr��ezi' 

Источник

How to Fix — UnicodeDecodeError: invalid start byte — during read_csv in Pandas

In this short guide, I’ll show you** how to solve the error: UnicodeDecodeError: invalid start byte while reading a CSV with Pandas**:

pandas UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0x97 in position 6785: invalid start byte

The error might have several different reasons:

In the next steps you will find information on how to investigate and solve the error.

As always all examples can be found in a handy: Jupyter Notebook

Step 1: UnicodeDecodeError: invalid start byte while reading CSV file

To start, let’s demonstrate the error: UnicodeDecodeError while reading a sample CSV file with Pandas.

The file content is shown below by Linux command cat :

We can see some strange symbol at the file start: ��

Using method read_csv on the file above will raise error:

df = pd.read_csv('../data/csv/file_utf-16.csv') 

UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xff in position 0: invalid start byte

Step 2: Solution of UnicodeDecodeError: change read_csv encoding

The first solution which can be applied in order to solve the error UnicodeDecodeError is to change the encoding for method read_csv .

To use different encoding we can use parameter: encoding :

df = pd.read_csv('../data/csv/file_utf-16.csv', encoding='utf-16') 

and the file will be read correctly.

The weird start of the file was suggesting that probably the encoding is not utf-8.

In order to check what is the correct encoding of the CSV file we can use next Linux command or Jupyter magic:

!file '../data/csv/file_utf-16.csv' 
../data/csv/file_utf-16.csv: Little-endian UTF-16 Unicode text 

Another popular encodings are:

Python has option to check file encoding but it may be wrong in some cases like:

with open('../data/csv/file_utf-16.csv') as f: print(f) 

Step 3: Solution of UnicodeDecodeError: skip encoding errors with encoding_errors=’ignore’

Pandas read_csv has a parameter — encoding_errors=’ignore’ which defines how encoding errors are treated — to be skipped or raised.

The parameter is described as:

How encoding errors are treated.

Note: Important change in the new versions of Pandas:

Changed in version 1.3.0: encoding_errors is a new argument. encoding has no longer an influence on how encoding errors are handled.

Let’s demonstrate how parameter of read_csv — encoding_errors works:

from pathlib import Path import pandas as pd file = Path('../data/csv/file_utf-8.csv') file.write_bytes(b"\xe4\na\n1") # non utf-8 character df = pd.read_csv(file, encoding_errors='ignore') 

The above will result into:

To prevent Pandas read_csv reading incorrect CSV data due to encoding use: encoding_errors=’strinct’ — which is the default behavior:

df = pd.read_csv(file, encoding_errors='strict') 

UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xe4 in position 0: invalid continuation byte

Another possible encoding error which can be raised by the same parameter is:

Pandas UnicodeEncodeError: ‘charmap’ codec can’t encode character

Step 4: Solution of UnicodeDecodeError: fix encoding errors with unicode_escape

The final solution to fix encoding errors like:

is by using option unicode_escape . It can be described as:

Encoding suitable as the contents of a Unicode literal in ASCII-encoded Python source code, except that quotes are not escaped. Decode from Latin-1 source code. Beware that Python source code actually uses UTF-8 by default.

Pandas read_csv and encoding can be used ‘unicode_escape’ as:

df = pd.read_csv(file, encoding='unicode_escape') 

to prevent encoding errors.

Resources

Источник

UnicodeDecodeError: ‘utf8’ codec can’t decode byte 0xa5 in position 0: invalid start byte

The UnicodeDecodeError occurs mainly while importing and reading the CSV or JSON files in your Python code. If the provided file has some special characters, Python will throw an UnicodeDecodeError: ‘utf8’ codec can’t decode byte 0xa5 in position 0: invalid start byte.

What is UnicodeDecodeError ‘utf8’ codec can’t decode byte?

The UnicodeDecodeError normally happens when decoding a string from a certain coding. Since codings map only a limited number of str strings to Unicode characters, an illegal sequence of str characters (non-ASCII) will cause the coding-specific decode() to fail.

When importing and reading a CSV file, Python tries to convert a byte-array (bytes which it assumes to be a utf-8-encoded string) to a Unicode string (str). It is a decoding process according to UTF-8 rules. When it tries this, it encounters a byte sequence that is not allowed in utf-8-encoded strings (namely this 0xff at position 0).

import pandas as pd a = pd.read_csv("filename.csv")
Traceback (most recent call last): UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 2: invalid start byte 

There are multiple solutions to resolve this issue, and it depends on the different use cases. Let’s look at the most common occurrences, and the solution to each of these use cases.

Solution for Importing and Reading CSV files using Pandas

If you are using pandas to import and read the CSV files, then you need to use the proper encoding type or set it to unicode_escape to resolve the UnicodeDecodeError as shown below.

import pandas as pd data=pd.read_csv("C:\\Employess.csv",encoding=''unicode_escape') print(data.head())

Solution for Loading and Parsing JSON files

If you are getting UnicodeDecodeError while reading and parsing JSON file content, it means you are trying to parse the JSON file, which is not in UTF-8 format. Most likely, it might be encoded in ISO-8859-1. Hence try the following encoding while loading the JSON file, which should resolve the issue.

json.loads(unicode(opener.open(. ), "ISO-8859-1"))

Solution for Loading and Parsing any other file formats

In case of any other file formats such as logs, you could open the file in binary mode and then continue the file read operation. If you just specify only read mode, it opens the file and reads the file content as a string, and it doesn’t decode properly.

You could do the same even for the CSV, log, txt, or excel files also.

with open(path, 'rb') as f: text = f.read()

Alternatively, you can use decode() method on the file content and specify errors=’replace’ to resolve UnicodeDecodeError

with open(path, 'rb') as f: text = f.read().decode(errors='replace')

When you call .decode() an a unicode string, Python 2 tries to be helpful and decides to encode the Unicode string back to bytes (using the default encoding), so that you have something that you can really decode. This implicit encoding step doesn’t use errors=’replace’ , so if there are any characters in the Unicode string that aren’t in the default encoding (probably ASCII) you’ll get a UnicodeEncodeError .

(Python 3 no longer does this as it is terribly confusing.)

Check the type of message and assuming it is indeed Unicode , works back from there to find where it was decoded (possibly implicitly) to replace that with the correct decoding.

Solution for decoding the string contents efficiently

If you encounter UnicodeDecodeError while reading a string variable, then you could simply use the encode method and encode into a utf-8 format which inturns resolve the error.

Источник

Читайте также:  Python datetime offset aware to offset naive
Оцените статью