2

I've got a problem with the encoding type of the file that i'm importing ( it contains polish special characters ). How do I make it work?

The error says:

Traceback (most recent call last):
  File "D:/Users/Denis/Dysk Google/scripts/python/napisy/napisy", line 6, in <module>
    str = inputfile.read() #name for the file
  File "D:\Python33\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 2: character maps to <undefined>

part that there is a problem with:

inputfilename = "a.txt"
outputfilename = inputfilename[0:-4]+"_fixed"+".txt"

inputfile = open(inputfilename, 'r')

str = inputfile.read() #name for the file

newstring = str.replace("œ", "s").replace("ê","e").replace("³","l").replace("¹","a").replace("¿","z").replace("ñ","n").replace("Ÿ","z").replace("æ","c")

outputfile = open(outputfilename, "w")
outputfile.write(newstring)
outputfile.close()
4
  • Is this Python 2 or Python 3? I suspect Python 2, but please verify. Commented Mar 1, 2014 at 22:19
  • It's python 3 (title). Commented Mar 1, 2014 at 22:20
  • Specify the correct encoding in the open call. Your system apparently has a default encoding of cp1252, but the file is encoded in some other encoding. Commented Mar 1, 2014 at 22:26
  • oh thanks! I tried with adding encoding to 'open' call but i didn't think about cp1250. Shame on me thanks :) Commented Mar 1, 2014 at 23:36

1 Answer 1

2

You should try 'cp1250' as encoding:

import codecs
content = None
with codecs.open('file-name', 'r', encoding='cp1250') as f:
    content = f.read()

print(content)

if this fails, you may also try ISO-8859-2 encoding

Sign up to request clarification or add additional context in comments.

1 Comment

encoding cp1250 works :) i tried with utf-8, iso etc... but it didn't work. I should listen to the errors more :) Thanks anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.