将重音字符从用户输入写入文本文件Python 3.7

问题描述 投票:0回答:1

您好我有以下代码片段:

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'),但它仍然给我错误。

python-3.7 python-unicode
1个回答
0
投票

设置以下环境变量为我修复了它。

export LANG=C.UTF-8
export LC_ALL=C.UTF-8

或另一种方法是通过:PYTHONIOENCODING="UTF-8" python3 writetest.py运行它

© www.soinside.com 2019 - 2024. All rights reserved.