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

如何用Python批量将指定文件夹下的.docx文件从ANSI转UTF-8?

批量转换指定文件夹下.docx文件编码为UTF-8

先说明:docx文件的编码特性

docx本质是XML压缩包,内部默认采用UTF-8编码存储文本。你遇到的编码问题大概率是读取时的编码解析错误,而非文件本身编码是ANSI。下面的代码会帮你遍历目标文件夹的所有docx文件,处理文本编码问题后重新保存为标准UTF-8格式的docx。

完整实现步骤

首先安装依赖库:

pip install python-docx unidecode

然后运行以下代码(记得替换文件夹路径):

import os
from docx import Document
from unidecode import unidecode

def convert_single_docx(input_path, output_path):
    # 读取目标docx文件
    doc = Document(input_path)
    
    # 遍历所有段落处理文本编码
    for para in doc.paragraphs:
        text = para.text
        if isinstance(text, str):
            try:
                # 针对ANSI(常见为cp1252编码)转UTF-8
                fixed_text = text.encode('latin-1').decode('utf-8', 'replace')
            except UnicodeEncodeError:
                # 编码无法转换时用unidecode做兼容处理
                fixed_text = unidecode(text)
        else:
            fixed_text = unidecode(text)
        # 替换段落文本
        para.text = fixed_text
    
    # 保存处理后的文件(默认UTF-8编码)
    doc.save(output_path)

def batch_process_folder(source_folder, target_folder):
    # 创建输出文件夹(不存在则新建)
    if not os.path.exists(target_folder):
        os.makedirs(target_folder)
    
    # 遍历源文件夹下的所有文件
    for filename in os.listdir(source_folder):
        # 只处理docx格式文件
        if filename.lower().endswith('.docx'):
            input_full_path = os.path.join(source_folder, filename)
            output_full_path = os.path.join(target_folder, f"converted_{filename}")
            
            print(f"正在处理:{filename}")
            convert_single_docx(input_full_path, output_full_path)
    
    print("所有文件处理完成!")

# -------------------------- 替换成你的文件夹路径 --------------------------
source_dir = "C:/你的源文件夹路径"
target_dir = "C:/你的输出文件夹路径"
# -------------------------------------------------------------------------

batch_process_folder(source_dir, target_dir)

使用注意事项

  • 把source_dir和target_dir替换成你实际的文件夹路径
  • 处理后的文件会以converted_原文件名.docx的形式保存在输出文件夹,不会覆盖原文件
  • 如果遇到特殊字符无法转换,unidecode会自动转成相近的可识别字符

内容的提问来源于stack exchange,提问作者Hellena Crainicu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 03:42:57