[Tutor] Encoding error when reading text files in Python 3
Dat Huynh
htdatcse at gmail.com
Sat Jul 28 11:34:36 CEST 2012
Dear all,
I have written a simple application by Python to read data from text files.
Current I have both Python version 2.7.2 and Python 3.2.3 on my laptop.
I don't know why it does not run on Python version 3 while it runs
well on Python 2.
Could you please tell me how I can run it on python 3?
Following is my Python code.
------------------------------
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print("Processing [" +file +"]...\n" )
f = open(rootdir+file, 'r')
data = f.read()
f.close()
print(data)
------------------------------
This is the error message:
------------------------------
Traceback (most recent call last):
File "/Users/dathuynh/Documents/workspace/PyTest/MyParser.py", line
53, in <module>
main()
File "/Users/dathuynh/Documents/workspace/PyTest/MyParser.py", line
20, in main
data = f.read()
File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/encodings/ascii.py",
line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position
4980: ordinal not in range(128)
------------------------------
Thank you very much for your help.
Sincerely,
Dat Huynh.
More information about the Tutor
mailing list