Sunday, May 5, 2024
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 895  / 3 Years ago, tue, october 26, 2021, 11:24:29

I'm trying to read the content of a text file, line by line, with this code:


import os.path  

file_to_read = open("file_name.txt", "r")
lines = file_to_read.readlines()

When I run it I get the following error:


enter image description here



Traceback (most recent call last):

File "D:/Files/test.py", line 4, in < module>

lines = file_to_read.readlines()

File "C:Program Files (x86)Microsoft Visual StudioSharedPython39_64libencodingscp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]

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



If I remove the last line, so the code looks like this:


import os.path  

file_to_read = open("file_name.txt", "r")

Then I don't get any errors.


enter image description here


Which points me towards a problem with lines = file_to_read.readlines(), but I cannot see anything wrong with it.


More From » command-line

 Answers
1

There's nothing wrong with lines = file_to_read.readlines(), but this is the line that actually reads the contents of the file. open() just opens it and does not proceed to read it.


Like the error tells you, python doesn't know how to decode byte 0x9d in position 260. Check the file encoding and also make sure the file isn't corrupt.


This answer may help you, too, (i.e., explicitly specify utf-8 encoding or whatever encoding the file uses). Essentially,


with open("file_name.txt", "r", encoding="utf-8") as file_to_read:
...

[#858] Wednesday, October 27, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
imonove

Total Points: 82
Total Questions: 113
Total Answers: 106

Location: Saint Vincent and the Grenadines
Member since Wed, Nov 3, 2021
3 Years ago
;