python - 编码类型错误 - python 3.x

标签 python file-io python-3.x encoding import

我导入的文件的编码类型有问题(它包含波兰语特殊字符)。我该如何让它发挥作用?

错误提示:

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>

有问题的部分:

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()

最佳答案

您应该尝试使用“cp1250”作为编码:

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

print(content)

如果失败,您也可以尝试 ISO-8859-2 编码

关于python - 编码类型错误 - python 3.x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22121108/

相关文章:

python - 什么是适合 Python 程序员的大中型项目?

python 列表理解 VS 行为

python - Python 中的 random.sample() 方法有什么作用?

java - 文件 IO 期间出现 NullPointerException

javascript - 在 Phonegap 中读取本地文件

python - 如何在完成代码的同时进行 pandas 列选择?

java - 从目录中读取文件并在java中的嵌套for循环中比较文件

python - Boto3 无效参数异常

python - 使用 for 循环生成列表

python - 如何查找两个DataFrame之间具有相同ID的所有记录?