编码转换-codecs
1.打开notepadd++, 创建一个文件testansi.txt,随意写一些内容,并保存为ansi 编码
2.打开Pycharm,新建AnsiToUTF8.py,创建如下代码,并运行。
#to support encodings import codecs #read input file with codecs.open("F:/Python_Code/testansi.txt", 'r', encoding = 'utf8') as file: lines = file.read() #write output file with codecs.open("F:/Python_Code/testutf8.txt", 'w', encoding = 'utf8') as file: file.write(lines)
运行结果,没有报错。
3.打开新生成的文件tesstutf8.txt,查看编码已经变成UTF8.
codecs可操作的编码类型很多,参考https://docs.python.org/3/library/codecs.html