在python中从windows-1252转换为utf-8

问题描述

我想在python中从windows-1252转换为utf-8,我写了这段代码:

def encode(input_file,output_file):
        f = open(input_file,"r")
        data = f.read()
        f.close()

        # Convert from Windows-1252 to UTF-8
        encoded = data.encode('Windows-1252').decode('utf-8')
        with safe_open_w(output_file) as f:
            f.write(encoded)

但我有这个错误:

encoded = data.encode('Windows-1252').decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe8 in position 5653: invalid continuation byte

我尝试使用此元标记转换 html:

<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">

解决方法

您转换的方式错误。您想从 cp1252 中解码,然后编码到 UTF-8。但后者并不是真正必要的。 Python 已经为您完成了。

当你解码某些东西时,输入应该是 bytes,结果是一个 Python 字符串。将字符串写入文件已隐式转换它,实际上您也可以通过指定编码来执行相同的读取操作。

此外,将整个文件读入内存是不优雅和浪费的。

with open(input_file,'r',encoding='cp1252') as inp,\
        open(output_file,'w',encoding='utf-8') as outp:
    for line in inp:
        outp.write(line)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...