如何更改文件中字符的编码

How to change encoding of characters from file

我已经阅读了很多关于编码的文章,但我仍然不确定我是否完全理解它。我有一个编码为 ANSI 的文件,其中包含单词 "Solluções"。我想将文件转换为 UTF-8,但每当我这样做时,它都会更改字符。

代码:

with codecs.open(filename_in,'r') 
   as input_file, 
   codecs.open(filename_out,'w','utf-8') as output_file:
   output_file.write(input_file.read())

结果:"Solluções"

我想这是一个愚蠢的问题,但我现在陷入了僵局。我尝试在写入文件之前对文件中的各个数据调用 encode('utf-8') 无济于事,所以我猜这也不正确......感谢任何帮助,谢谢!

类似问题的SO answer指定文件的输入类型,如codecs.open(sourceFileName, "r", "your-source-encoding")。否则,如果无法检测到原始编码,python 可能无法正确解释字符。

关于编码的警告:大多数谈论 ANSI 的人指的是 Windows 代码页之一;您可能真的有一个 CP(代码页)1252 的文件,它几乎与 ISO-8859-1(拉丁语 1)相同,但又不完全相同。如果是这样,请使用 cp-1252 而不是 latin-1 作为 your-source-encoding.

你可以试试

  from codecs import encode,decode
  with open(filename_out,"w") as output_file:
       decoded_unicode = decode(input_file.read(),"cp-1252") #im guessing this is what you mean by "ANSI"
       utf8_bytes = encode(decoded_unicode,"utf8")
       output_file.write(utf8_bytes)