Unicodedecodeerror charmap codec can t decode byte

I’m trying to get a Python 3 program to do some manipulations with a text file filled with information. However, when trying to read the file I get the following error:

Traceback (most recent call last):
File "SCRIPT LOCATION", line NUMBER, in
text = file.read()
File "C:Python31libencodingscp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: ‘charmap’ codec can’t decode byte 0x90 in position 2907500: character maps to

6 Answers 6

The file in question is not using the CP1252 encoding. It’s using another encoding. Which one you have to figure out yourself. Common ones are Latin-1 and UTF-8 . Since 0x90 doesn’t actually mean anything in Latin-1 , UTF-8 (where 0x90 is a continuation byte) is more likely.

You specify the encoding when you open the file:

Just to add in case file = open(filename, encoding="utf8") does not work try file = open(filename, errors=’ignore’)

If you can’t tell what encoding your file uses and the solution above does not work (it’s not utf8 ) and you found yourself merely guessing — there are online tools that you could use to identify what encoding that is. They aren’t perfect but usually work just fine. After you figure out the encoding you should be able to use solution above.

EDIT: (Copied from comment)

A quite popular text editor Sublime Text has a command to display encoding if it has been set.

  1. Go to View -> Show Console (or Ctrl + ` )

  1. Type into field at the bottom view.encoding() and hope for the best (I was unable to get anything but Undefined but maybe you will have better luck. )

Alternatively if you don’t need to decode the file, such as uploading the file to a website, open(filename, ‘rb’) . r = reading, b = binary

Читайте также:  Фикса для дырок под смеситель в мойке

TLDR? Try: file = open(filename, encoding=’cp437)

Why? When one use:

Python assumes the file uses the same codepage as current environment (cp1252 in case of the opening post) and tries to decode it to its own default UTF-8. If the file contains characters of values not defined in this codepage (like 0x90) we get UnicodeDecodeError. Sometimes we don’t know the encoding of the file, sometimes the file’s encoding may be unhandled by Python (like e.g. cp790), sometimes the file can contain mixed encodings.

If such characters are unneeded, one may decide to replace them by question marks, with:

Another workaround is to use:

The characters are then left intact, but other errors will be masked too.

Quite good solution is to specify the encoding, yet not any encoding (like cp1252), but the one which has ALL characters defined (like cp437):

Codepage 437 is the original DOS encoding. All codes are defined, so there are no errors while reading the file, no errors are masked out, the characters are preserved (not quite left intact but still distinguishable).

Пытаюсь читать файл портов от IANA. Он сохранен в кодировке UTF-8 w/o BOM. Но на одной из строк функция readline() ругается вот таким вот образом

‘charmap’ codec can’t decode byte 0x98 in position 7938: character maps to

Строка в файле выглядит следующим образом:

Какой костыль придумать для этого? Или есть прямой путь решения?

UPD

Ибо костыль в виде удаления данной строки пойдет (причем она, почему-то вот такая одна), но только на время отладки, ибо потом вдруг что, партнеры будут рвать волосы на моей голове. Так же выложу код, которым пользуюсь для данной операции:

Читайте также:  Разрешение формата а3 в пикселях

4 ответа 4

попробуйте использовать встроенную библиотеку codecs:

Чтобы прочитать текстовый файл, закодированный с использованием utf-8 кодировки в Питоне, можно использовать io.open() функцию, которая доступна как встроенная open() в Питоне 3:

Если в файле возможны ошибки, связанные с кодировкой: сама кодировка верна, но могут быть мелкие погрешности, тогда можно передать errors=’ignore’ обработчик ошибок (или другое значение в зависимости от конкретной ситуации).

Не используйте codecs , который может некорректно работать с режимом универсальных строк.
Не нужно менять вашу кодовую страницу на cp65001 , чтобы utf-8 файл прочитать.
Если хотите напечатать Unicode в Виндовую консоль, то см. Как из Python вывести на Windows-консоль строку в Юникоде?

Подскажите как правильно прочитать файл? Уже всю голову сломал.

  • Вопрос задан более трёх лет назад
  • 3374 просмотра

видно что происходит попытка перекодировать из любимой винодовой cp1251 🙂 а файл видать в UTF8.
попробуй открыть как ‘rb’ и конвертировать построчно

а вообще хорошо бы знать, в какой кодировке файл.

Оцените статью
Добавить комментарий

Adblock
detector