J'utilise Python 2.6.1 et j'ai un problème lié à utf-8 avec mon code. Ce problème est reproductible avec ce code:Python utf-8 handling
# -*- coding: utf-8 -*-
import os, sys
import string, time
import codecs, re
bDATA='"Domenick Lombardozzi","Eddie Marsan","Isaach De Bankolé","John Hawkes"'
print (bDATA)
fileObj = codecs.open("btvresp1.txt", "r", "utf-8")
data = fileObj.read()
print (data)
La première impression de bDATA
fonctionne très bien. Toutefois, si les mêmes données dans le fichier fichier btcresp1.txt, python se plaint comme suit:
cat btvresp2.txt
"Domenick Lombardozzi","Eddie Marsan","Isaach De Bankol?","John Hawkes"
python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> # -*- coding: utf-8 -*-
...
>>> import os, sys
>>> import string, time
>>> import codecs, re
>>> bDATA='"Domenick Lombardozzi","Eddie Marsan","Isaach De Bankol","John Hawkes"'
>>> print (bDATA)
"Domenick Lombardozzi","Eddie Marsan","Isaach De Bankol","John Hawkes"
>>> fileObj = codecs.open("btvresp2.txt", "r", "utf-8")
>>> data = fileObj.read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/codecs.py", line 666, in read
return self.reader.read(size)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/codecs.py", line 472, in read
newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 55-57: invalid data
Je ne suis pas sûr de savoir pourquoi les mêmes données lorsqu'elles sont lues à partir d'un fichier provoque des problèmes. Quelqu'un peut-il éclaircir pourquoi ce comportement et comment je peux résoudre ce problème?
Merci d'avance!
Etes-vous sûr que le fichier btvresp1.txt est codé en utf-8? – nos