0

I get a UnicodeDecodeError trying to execute the below code in python 3.6.12

import csv

fh = open('./testLog.log', 'r')
d = csv.DictReader(fh, delimiter=" ")
for row in d:
    print(row)

fh.close()

File "/opt/rh/rh-python36/root/usr/lib64/python3.6/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 2826: ordinal not in range(128)

But when the same code is executed on python 3.9.7, it executes without any error. I am guessing the below text from csv is causing the problem

soe-admin�~@~Ys%20MacBook%20Pro

How can I fix this?

Ahtesham Akhtar
  • 203
  • 2
  • 13
  • check `locale.getpreferredencoding()` what is default encoding tacking place, if it set to ascii , change it to UTF-8 – sahasrara62 Apr 26 '23 at 06:40

1 Answers1

0

Try this if it works

import csv

fh = open('./testLog.log', 'r', encoding='utf-8')
d = csv.DictReader(fh, delimiter=" ")
for row in d:
    print(row)

fh.close()
Ajeet Verma
  • 2,938
  • 3
  • 13
  • 24