M
M
Mark Adams2016-03-24 01:12:36
Python
Mark Adams, 2016-03-24 01:12:36

How to fix encoding error when reading cvs file?

I want to read a file in a loop in python 3:

f = open(name, 'r')

for i in f:
  print(i)

We have:
UnicodeDecodeError: 'ascii' codec can't decode byte 0x8f in position 36: ordinal not in range(128)
How is this solved through codecs?
I read many articles about Unicode, but nothing helps. No one can give an adequate and simple answer to the question.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sim3x, 2016-03-24
@sim3x

https://docs.python.org/3.1/library/csv.html

import csv
with open('some.csv', newline='', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

D
Dimonchik, 2016-03-24
@dimonchik2013

body = body.decode('utf8', 'ignore')
if it doesn't help - cut out the left characters,
you can try to guess the encoding instead of utf8
https://pypi.python.org/pypi/chardet

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question