Python中如何将cp866编码的文件内容转换为UTF-8编码后打印
你用encoding='cp866'参数打开文件时,Python内部已经自动完成了CP866字节到Unicode字符串的解码,你只需要把Unicode字符串编码为UTF-8输出即可,具体实现分场景参考以下方案:
场景1:直接在终端打印
如果你的运行终端默认支持UTF-8编码,直接读取内容打印即可:
# 建议用with语法自动管理文件句柄,避免资源泄漏 with open(file_name, 'r', encoding='cp866') as input_file: for line in input_file: print(line, end='')
如果终端打印出现乱码,可以手动指定编码输出,绕过系统默认编码配置:
import sys with open(file_name, 'r', encoding='cp866') as input_file: for line in input_file: # 把Unicode字符串编码为UTF-8字节,直接写入标准输出缓冲区 sys.stdout.buffer.write(line.encode('utf-8'))
场景2:输出为UTF-8编码的文件
如果需要把转码后的内容持久化存储,直接指定输出文件的编码为UTF-8即可:
with open(file_name, 'r', encoding='cp866') as input_file, \ open('utf8_output.txt', 'w', encoding='utf-8') as output_file: for line in input_file: output_file.write(line)
内容的提问来源于stack exchange,提问作者rokibox
相关产品推荐
相关产品推荐

