Python版本有所不同。下面是Python的3.6:
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print('\ufb01')
fi
>>> with open('out.txt','w') as f:
... f.write('\ufb01')
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "D:\dev\Python36\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\ufb01' in position 0: character maps to <undefined>
在這種情況的原因是Python的3.6在Windows寫入使用Unicode API的控制檯上,所以它很好地工作。使用默認編碼打開文件使用我的系統上的代碼頁1252,該代碼頁不支持編寫的Unicode字符。使用支持所有Unicode字符的編碼:
>>> with open('out.txt','w',encoding='utf8') as f:
... f.write('\ufb01')
...
1
嘗試使用'f.write(convert()。encode('utf-8')) – Hackerman