You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 21:27:05