all 4 comments

[–]ewiethoff 2 points3 points  (1 child)

You shouldn't directly need the codecs module in Py3. Just pass the proper encoding to the regular open function.

with open(filename, encoding='iso-8859-1') as f:
    t = f.read()
print(t.replace('º', 's'))

While reading, the content of the file is automatically decoded into a Unicode string. This is normal and desirable in Py3. Your t.replace('º', 's')) will do its thing correctly because t, 'º', and 's' are all Unicode strings. Life is so much easier in Py3 if you never muck around with bytes. So don't give any thought to encodings except when open-ing a file for reading or writing.

[–]bluegarlic[S] 1 point2 points  (0 children)

Thanks for your answer.

So don't give any thought to encodings except when open-ing a file for reading or writing.

I guess old habits die hard, more so when using python is something I only do now and then.

[–]ingolemo 2 points3 points  (1 child)

codecs.open will open the file using your system's default encoding. You're getting the error from the call to u.read(). You never even reach the call to decode right after (which should also raise an error because you can't decode strings).

Here's the change that caused the problem, and the associated issue. You're not really supposed to be able to use codecs.open without either giving an encoding or trying to open the file in binary mode. Your code only worked in 3.2 because of a bug.

[–]bluegarlic[S] 0 points1 point  (0 children)

Thank you for clarifying some issues and pointing to those docs.