all Python 3Files & I/Oterm
errors=
open() parameters
The open() parameter that decides what happens on an encoding error: 'strict' (the default, raises), 'ignore', 'replace', 'backslashreplace'.
Syntax
open(file, encoding='utf-8', errors='strict')
'ignore' and 'replace' do not repair anything, they silently destroy data: bytes either vanish or turn into U+FFFD, and the original is gone for good — figure out the file's real encoding first. When the job is read, edit, write back, use errors='surrogateescape': it is the only one of these that round-trips undecodable bytes intact. The parameter is rejected in binary mode, where nothing is decoded at all.
Examples
with open('broken.txt', 'wb') as f:
f.write('привет'.encode('utf-8') + b'\xff')
# игнорировать некорректные байты
with open('broken.txt', encoding='utf-8', errors='ignore') as f:
print(f.read()) # → привет
# заменить их символом-заменителем
with open('broken.txt', encoding='utf-8', errors='replace') as f:
print(f.read()) # → привет� — символ-заменитель
with open('broken.txt', encoding='utf-8') as f:
f.read() # → UnicodeDecodeError: по умолчанию errors='strict'
See also
Open in the full glossarydocs.python.orgReport an inaccuracy