When I first started messing around with python strings and unicode, It took me awhile to understand the jargon of decode and encode too, so here's my post from here that may help:


Think of decoding as what you do to go from a regular bytestring to unicode and encoding as what you do to get back from unicode. In other words:

You de-code a str to produce a unicode string (in Python 2)

and en-code a unicode string to produce a str (in Python 2)

So:

unicode_char = u'\xb0'

encodedchar = unicode_char.encode('utf-8')

encodedchar will contain your unicode character, displayed in the selected encoding (in this case, utf-8).

The same principle applies to Python 3. You de-code a bytes object to produce a str object. And you en-code a str object to produce a bytes object.

Answer from Aphex on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › best solution for unicodedecodeerror ?
r/learnpython on Reddit: Best solution for UnicodeDecodeError ?
July 5, 2021 -

I'm processing text that comes from the internet and the script keeps exiting with a unicode decode error.

I need this problem to 100% go away and it doesn't matter if the text is encoded properly for the sake of my project, so this problem is really frustrating.

I have verified there are indeed bad unicode characters causing the script to exit, but it's just so frustrating that python doesn't throw a warning instead of exiting as the script would run perfectly if it didn't.

If I have to use a regex to filter out all non alphanumeric/punctuation characters then I will, but I am assuming there is a better solution.

Error:

Traceback (most recent call last):

File "process.py", line 23, in <module>

read_content =file.read()

File "C:\Users\removed\Anaconda3\envs\dev1\lib\encodings\cp1252.py", line 23, in decode

return codecs.charmap_decode(input,self.errors,decoding_table)[0]

Code:

file = open(i, 'r', encoding='utf-8', errors='ignore')

read_content = file.read()

file.close()
Discussions

How to get python to tolerate UTF-8 encoding errors - Stack Overflow
I have a set of UTF-8 texts I have scraped from web pages. I am trying to extract keywords from these files like so: import os import json from rake_nltk import Rake rake_nltk_var = Rake() director... More on stackoverflow.com
🌐 stackoverflow.com
utf 8 - Decode byte to utf-8 in Python: 'errors="ignore"' not working - Stack Overflow
Question: I read the docs and put errors="ignore" in my code but it isn't working! Why? ... You have an Encode error, caused by trying to print Unicode text to a Windows console that can't handle your text. ... This is why the traceback is important; look at that too, not just the exception you get. The traceback would have shown you that the error takes place on the print(html) line, not the line with the html.decode... More on stackoverflow.com
🌐 stackoverflow.com
April 1, 2017
UnicodeDecodeError in Python when reading a file, how to ignore the error and jump to the next line? - Stack Overflow
Your file doesn't appear to use the UTF-8 encoding. It is important to use the correct codec when opening a file. You can tell open() how to treat decoding errors, with the errors keyword: More on stackoverflow.com
🌐 stackoverflow.com
python - unicode decode error: how to skip invalid characters - Stack Overflow
Additional information which would ... that the errors='ignore' can also be added to the open command so that if you are doing a with open you don't have to temporarily go to binary. 2018-11-18T21:03:44.523Z+00:00 ... I think your text file have some special character, so 'utf-8' can't decode... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
github.com › paulscherrerinstitute › py_elog › issues › 5
.decode('utf-8') throws an error if not utf-8; suggest to add `'ignore'` ? · Issue #5 · paulscherrerinstitute/py_elog
September 26, 2018 - should .decode('utf-8') be exchanged with .decode('utf-8','ignore') ? or some optional toggle? https://docs.python.org/3/howto/unicode.html#the-string-type · py_elog/elog/logbook.py · Line 258 in b75a715 · returned_msg = resp_message.decode('utf-8').splitlines() py_elog/elog/logbook.py · Line 361 in b75a715 · if re.findall('<td.*?class="errormsg".*?>.*?</td>', resp_message.decode('utf-8'), flags=re.DOTALL): py_elog/elog/logbook.py ·
Author   paulscherrerinstitute
🌐
Johnlekberg
johnlekberg.com › blog › 2020-04-03-codec-errors.html
Handling encoding and decoding errors in Python
April 3, 2020 - The default strategy (errors="strict") raises an exception when an error occurs. But, sometimes you want your program to continue processing data, either by omitting bad data (errors="ignore") or by replacing bad data with replacement characters (errors="replace").
🌐
Google Groups
groups.google.com › g › comp.lang.python › c › UfXqjKRnIxo
using DictReader() with .decode('utf-8', 'ignore')
(python 3) > with open(dfile, 'rb') as f: > for line in f: > > line > = line.decode('utf-8', 'ignore').split(',') > > How can I ​do accomplish decode('utf-8', 'ignore') when reading with > DictReader() Which DictReader? Do you mean the one in the csv module? I will assume so. I haven't tried it, but I think something like this will work: # untested with open(dfile, 'r', encoding='utf-8', errors='ignore', newline='') as f: reader = csv.DictReader(f) for row in reader: print(row['fieldname']) -- Steven
🌐
Delft Stack
delftstack.com › home › howto › python › decode utf 8 python
How to Decode UTF-8 in Python | Delft Stack
February 12, 2024 - We then decode the same bytes with errors='ignore' and errors='replace'. With 'ignore', the invalid sequence is simply skipped, and with 'replace', it’s replaced with the Unicode replacement character �. ... In Python, handling files with ...
🌐
Python
docs.python.org › 3 › library › codecs.html
codecs — Codec registry and base classes
Changed in version 3.2: Before 3.2, the errors argument was ignored; 'replace' was always used to encode, and 'ignore' to decode. Changed in version 3.3: Support any error handler. This module implements a variant of the UTF-8 codec. On encoding, a UTF-8 encoded BOM will be prepended to the UTF-8 encoded bytes.
🌐
Python documentation
docs.python.org › 3 › howto › unicode.html
Unicode HOWTO — Python 3.14.6 documentation
>>> b'\x80abc'.decode("utf-8", "strict") Traceback (most recent call last): ... UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte >>> b'\x80abc'.decode("utf-8", "replace") '\ufffdabc' >>> b'\x80abc'.decode("utf-8", "backslashreplace") '\\x80abc' >>> b'\x80abc'.decode("utf-8", "ignore") 'abc'
Find elsewhere
🌐
OneUptime
oneuptime.com › home › blog › how to fix 'unicodedecodeerror' in python
How to Fix 'UnicodeDecodeError' in Python
January 23, 2026 - Python's open() and decode() support error handling modes: # 'ignore' - skip problematic bytes with open('data.txt', 'r', encoding='utf-8', errors='ignore') as f: content = f.read() # Missing characters where errors occurred # 'replace' - replace ...
🌐
codelessgenie
codelessgenie.com › blog › unicodedecodeerror-in-python-when-reading-a-file-how-to-ignore-the-error-and-jump-to-the-next-line
Python UnicodeDecodeError: How to Ignore Errors and Skip Lines When Reading a File with Non-ASCII Characters — CodeLessGenie.com
Python’s open() function accepts an errors parameter to specify how to handle decoding errors. The most useful values are: ... with open("file.txt", "r", encoding="utf-8", errors="ignore") as f: content = f.read() print(content) # Undecodable ...
🌐
Bobby Hadz
bobbyhadz.com › blog › python-remove-non-utf-8-characters-from-string
Remove the non utf-8 characters from a String in Python | bobbyhadz
Copied!with open('example.txt', 'r', encoding='utf-8') as f: lines = f.readlines() for line in lines: line = line.encode( 'utf-8', errors='ignore' ).decode('utf-8') print(line) ...
🌐
Stack Overflow
stackoverflow.com › questions › 41451081 › decode-byte-to-utf-8-in-python-errors-ignore-not-working
utf 8 - Decode byte to utf-8 in Python: 'errors="ignore"' not working - Stack Overflow
April 1, 2017 - Question: I read the docs and put errors="ignore" in my code but it isn't working! Why? ... You have an Encode error, caused by trying to print Unicode text to a Windows console that can't handle your text. ... This is why the traceback is important; look at that too, not just the exception you get. The traceback would have shown you that the error takes place on the print(html) line, not the line with the html.decode() call.
Top answer
1 of 1
111

Your file doesn't appear to use the UTF-8 encoding. It is important to use the correct codec when opening a file.

You can tell open() how to treat decoding errors, with the errors keyword:

errors is an optional string that specifies how encoding and decoding errors are to be handled–this cannot be used in binary mode. A variety of standard error handlers are available, though any error handling name that has been registered with codecs.register_error() is also valid. The standard names are:

  • 'strict' to raise a ValueError exception if there is an encoding error. The default value of None has the same effect.
  • 'ignore' ignores errors. Note that ignoring encoding errors can lead to data loss.
  • 'replace' causes a replacement marker (such as '?') to be inserted where there is malformed data.
  • 'surrogateescape' will represent any incorrect bytes as code points in the Unicode Private Use Area ranging from U+DC80 to U+DCFF. These private code points will then be turned back into the same bytes when the surrogateescape error handler is used when writing data. This is useful for processing files in an unknown encoding.
  • 'xmlcharrefreplace' is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference &#nnn;.
  • 'backslashreplace' (also only supported when writing) replaces unsupported characters with Python’s backslashed escape sequences.

Opening the file with anything other than 'strict' ('ignore', 'replace', etc.) will then let you read the file without exceptions being raised.

Note that decoding takes place per buffered block of data, not per textual line. If you must detect errors on a line-by-line basis, use the surrogateescape handler and test each line read for codepoints in the surrogate range:

import re

_surrogates = re.compile(r"[\uDC80-\uDCFF]")

def detect_decoding_errors_line(l, _s=_surrogates.finditer):
    """Return decoding errors in a line of text

    Works with text lines decoded with the surrogateescape
    error handler.

    Returns a list of (pos, byte) tuples

    """
    # DC80 - DCFF encode bad bytes 80-FF
    return [(m.start(), bytes([ord(m.group()) - 0xDC00]))
            for m in _s(l)]

E.g.

with open("test.csv", encoding="utf8", errors="surrogateescape") as f:
    for i, line in enumerate(f, 1):
        errors = detect_decoding_errors_line(line)
        if errors:
            print(f"Found errors on line {i}:")
            for (col, b) in errors:
                print(f" {col + 1:2d}: {b[0]:02x}")

Take into account that not all decoding errors can be recovered from gracefully. While UTF-8 is designed to be robust in the face of small errors, other multi-byte encodings such as UTF-16 and UTF-32 can't cope with dropped or extra bytes, which will then affect how accurately line separators can be located. The above approach can then result in the remainder of the file being treated as one long line. If the file is big enough, that can then in turn lead to a MemoryError exception if the 'line' is large enough.

🌐
GitHub
gist.github.com › miraculixx › 84ac194c77f04817eeb3
Tired of Python's UnicodeDeocodeError, ascii codec can't decode? Here's how to fix it, once and for all. · GitHub
trying ('z\xc3\xbcrich',) ==> DID NOT WORK: zürich (type <type 'str'>) trying (u'z\xfcrich', 'utf-8') ==> DID NOT WORK: zürich (type <type 'unicode'>) trying (u'z\xfcrich',) ==> zürich worked (type <type 'unicode'>) trying ('z\xc3\xbcrich', 'utf-8') ==> zürich worked (type <type 'str'>) trying (u'Z\xfcrich',) ==> Zürich worked (type <type 'unicode'>) trying (u'Z\xfcrich',) ==> Zürich worked (type <type 'unicode'>) trying ('Z\xc3\xbcrich', 'utf-8') ==> Zürich worked (type <type 'str'>) trying ('Z\xc3\xbcrich', 'utf-8') ==> Zürich worked (type <type 'str'>)
🌐
Tutorialspoint
tutorialspoint.com › python › string_decode.htm
Python String decode() Method
Str.decode(encoding='UTF-8',errors='strict') The following are the parameters of the python string decode() function. encoding − This parameter specifies the encodings to be used. For a list of all encoding schemes, please visit: Standard Encodings. errors − This parameter specifies an error handling scheme. The default for errors is 'strict' which means that the encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error().
🌐
Wordpress
hclxing.wordpress.com › 2019 › 10 › 24 › how-to-ignore-python3-stdin-encoding-error
How to ignore Python3 stdin encoding error? | My Not-So-Boring Life
October 24, 2019 - #!/usr/bin/env python3 import sys sys.stdin.reconfigure(errors='ignore') for line in sys.stdin: print("RECEIVED:" + line.rstrip())
🌐
Python Module of the Week
pymotw.com › 2 › codecs
codecs – String encoding and decoding - Python Module of the Week
$ python codecs_decode_error.py strict Original : u'pi: \u03c0' File contents: ff fe 70 00 69 00 3a 00 20 00 c0 03 ERROR: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte · Switching to ignore causes the decoder to skip over the invalid bytes.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-strings-decode-method
Python Strings decode() method - GeeksforGeeks
May 11, 2026 - 2. errors (Optional): Specifies how to handle errors during decoding: strict (default): Raises an error for invalid characters. ignore: Ignores errors and proceeds. replace: Replaces invalid characters with a placeholder.