我有点努力让python阅读这个特定的文本文件。 (图1)
我尝试了一些编码(utf-8,ascii ..) 但都没有效果。 过了一会儿,我在追溯中找到了解决方案。 (图2)
现在我的问题是当python正在读取正确的编码时,这是如何导致错误的?
图1:
rel_path = "DIR/text.txt"
print ('Getting data from: ' + rel_path + ': \n')
text_file = open(rel_path)
print (text_file.read())
图2:
File "test.py", line 14, in <module>
print (text_file.read())
File "LOCALDIR\Python\Python35\lib\encodings\cp850.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2018' in position 4590:
character maps to <undefined>
注意文件python读取PYTHONDIR \ cp850.py&lt; -
当我在打开文本文件时添加 encoding ='cp850'时,它可以正常工作。 (图3)
图3:
rel_path = "DIR/text.txt"
print ('Getting data from: ' + rel_path + ': \n')
text_file = open(rel_path, encoding='cp850')
print (text_file.read())