Python UnicodeDecodeError: charmap codec can't decode byte error solution
Find the actual encoding value in Python file read error; Apply UTF-8, UTF-8 BOM and Windows-1254 differences without losing data.
Reading text file in PythonUnicodeDecodeError: 'charmap' codec can't decode byteerror indicates that the file's bytes could not be converted to text with the selected character encoding. This error can especially occur in codes that rely on the platform's default encoding.
The permanent solution is to find out the actual encoding of the file and specify it explicitly during reading. If you have verified that the file is UTF-8encoding="utf-8"use it. Writing UTF-8 to every file is not the only solution; Old Windows files may use other encodings.
Difference between decode and encode error
Decode converts bytes to Unicode text. Encode converts text into bytes. Therefore, during file readingUnicodeDecodeErrorseen when printing to the terminal withUnicodeEncodeErrorIt does not occur at the same stage. Identify the line in the error trace; simply changing the console encoding may not fix the file reading problem.
The codec name and byte position in the error message are valuable for diagnosis.charmapThe statement alone does not tell you what encoding the file is in. Indicates that a byte could not be matched in a particular table; The system where the source file was produced should also be examined.
1. Read UTF-8 file with open encoding
from pathlib import Path
text = Path("veri.txt").read_text(encoding="utf-8")
print(text)
same processopenwith:
with open("veri.txt", "r", encoding="utf-8") as stream:
text = stream.read()
Save the files you just created with the same convention:
Path("sonuc.txt").write_text("İstanbul, çığ, şeker", encoding="utf-8")
The fact that the Python source file in which the code is saved is UTF-8 does not make the external file it reads UTF-8. The encoding parameter here determines how to interpret the bytes of the external file.
2. utf-8-sig on files containing UTF-8 BOM
Some tools add BOM to the beginning of the UTF-8 file. Straightutf-8read this\ufeffcan preserve its character; The first column name of the CSV may change unexpectedly.utf-8-sigreads by removing the initial UTF-8 BOM.
import csv
with open("liste.csv", encoding="utf-8-sig", newline="") as stream:
reader = csv.DictReader(stream)
for row in reader:
print(row)
This option does not convert a UTF-16 or Windows-1254 file to UTF-8. First bytes of the fileFF FEor FE FFIf so, the possibility of UTF-16 should be evaluated separately.
3. cp1254 in old Turkish Windows files
Codec name in Python if the application producing the file reports using Windows-1254cp1254it could be. You can read the known encoding and create a new UTF-8 file:
from pathlib import Path
source = Path("eski.txt")
text = source.read_text(encoding="cp1254")
Path("yeni-utf8.txt").write_text(text, encoding="utf-8")
Keep the original file. Especially in the outputİ, ı, Ş, ş, Ğ, ğcompare their characters and a few actual records. Just because a decoder doesn't give errors doesn't prove that it produces correct text. An incorrect single-byte encoding can accept all bytes and create meaningless characters.
4. If encoding is unknown, examine bytes and source
raw = Path("veri.txt").read_bytes()
print(raw[:16].hex())
The most reliable way is to find out which application produced the file with which export setting. BOM, format definition or manufacturer information is helpful. Coding prediction tools generate probability; It may not give accurate results in short text and similar coding. If the file is actually a PDF, image, or ZIP, do not decode it as a text file.
Why isn't errors=ignore the final solution?
errors="ignore"Discards undecipherable bytes. Loss of customer name, address, product code or accounting data may occur.errors="replace"replaces it with a special character; It can be used to record corrupted data, but it does not restore the lost character.
Keep the default strict behavior in the data transfer job. Converting the read text back into bytes with the chosen encoding provides a technical consistency check; Again, source information and character comparison is required to prove actual encoding. If there are mixed codings in the file, correction or record-by-record parsing may be required on the manufacturer's side.
Short guide
Common mistake
Trying different encoding values one by one and accepting the first result that does not give an error as correct. The result should be readable and consistent with the source.