报错提示:
UnicodeEncodeError: 'gbk' codec can't encode character '\xa0' in position 0: illegal multibyte sequence
问题分析
因为windows默认使用gbk作为默认字符编码格式,所以python以utf8写入失败。
这里强制python打开windows文件的时候,以utf8格式。
解决方案:
- 方法1
设置环境变量PYTHONIOENCODING
C:\> set PYTHONIOENCODING=utf8
C:\> test.py > out.txt
- 方法2
设置环境变量 PYTHONUTF8
set PYTHONUTF8=1
- 方法3
在python命令行加入-X参数指定utf8
python -Xutf8 test.py > 3.txt
参考资料
Error occurs when trying to redirect Python UTF-8 stdout to a file on Windows - Stack Overflow
Python: Use the UTF-8 mode on Windows! - DEV Community
1. Command line and environment — Python 3.9.6 documentation
网友评论