我在生产系统中遇到错误,但我无法在开发环境中重现该错误:
with io.open(file_name, 'wt') as fd:
fd.write(data)
异常(exception):
File "/home/.../foo.py", line 18, in foo
fd.write(data)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 6400: ordinal not in range(128)
我已经尝试将很多奇怪的字符放入变量 data
中。
但到目前为止,我无法重现 UnicodeEncodeError
。
data
中需要包含什么才能得到 UnicodeEncodeError
?
更新
python -c 'import locale; print locale.getpreferredencoding()'
UTF-8
更新2
如果我通过 shell 和网络请求调用 locale.getpreferredencoding()
,编码是“UTF-8”。
我在我的代码中更新了我的异常处理并记录了 getpreferredencoding()
几天以来。现在又发生了(到现在我还不能强制或重现这个),编码是“ANSI_X3.4-1968”!
我不知道这个编码是在哪里设置的....
这使我的问题转向了不同的方向。留下这个问题没有用。我现在的问题是:首选编码在哪里更改?但这不是这个问题的一部分。
非常感谢所有的人
最佳答案
您依赖平台的默认编码;当默认编码不支持您写入文件的 Unicode 字符时,您会遇到编码异常。
encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever
locale.getpreferredencoding()
returns), but any encoding supported by Python can be used.
对于您的具体情况,locale.getpreferredencoding()
返回的默认值是 ASCII,因此 ASCII 范围之外的任何 Unicode 字符都会导致此问题,U-0080 及以上。
请注意,语言环境取自您的环境;如果它是 ASCII,这通常意味着语言环境设置为 POSIX default locale, C
.
明确指定编码:
with io.open(file_name, 'wt', encoding='utf8') as fd:
fd.write(data)
我以 UTF-8 为例;您选择什么完全取决于您的用例和您尝试写出的数据。
关于python - 如何重现 UnicodeEncodeError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41568129/