1 Simple Step to Solve Python .Read() Empty Result or UnicodeDecodeError Issue

Solution to no result output or error message UnicodeDecodeError when using read()

fylim
1 min readOct 20, 2023
Photo by David Pupăză on Unsplash

Issue

When using .read()to read an input file to a string, you receive either a UnicodeDecodeError or no output is given.

#Code with Issue

#open text file in read mode
text_file = open("C:/path/.txt", "r")

#read whole file to a string
data = text_file.read()

#close file
text_file.close()

print(data)
#ErrorMessage

File ~\AppData\Local\Programs\Python\Python310\lib\encodings\cp1252.py:23 in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]

UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 294: character maps to <undefined>

Solution

To fix this issue, specify the encoding for your input file when using .read() . We will specify “utf-8” as our encoding type in this case.

#Code Solution

#open text file in read mode (fix this step)
text_file = open("C:/path/.txt", "r", encoding="utf8")

#read whole file to a string
data = text_file.read()

#close file
text_file.close()

print(data)

Your input data should then load successfully.

--

--