您好我有以下代码片段:
while True:
try:
entry = input("Input element: ")
print (entry)
with open(fileName,'a',encoding='UTF-8') as thisFile:
thisFile.write(entry)
except KeyboardInterrupt:
break
这个基本上连续获取输入并将其写入文件,直到手动中断。但是,当用户输入类似Ñ的东西时。它输出:UnicodeEncodeError: 'utf-8' codec can't encode characters in position 0-1: surrogates not allowed
我明确地把utf-8编码,甚至尝试拉丁-1但仍然是相同的错误。我也把# -*- coding: utf-8 -*-
放在我的代码之上,并尝试了thisFile.write(entry.encode('utf-8')
,但它仍然给我错误。
设置以下环境变量为我修复了它。
export LANG=C.UTF-8
export LC_ALL=C.UTF-8
或另一种方法是通过:PYTHONIOENCODING="UTF-8" python3 writetest.py
运行它