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

Python 3.12导出DataFrame为CP1252编码TXT失败求助

问题

我从UTF-8编码的TXT文件和XML文件导入数据,将两种格式的数据分别转换后存入不同的pandas DataFrame,再将每个DataFrame导出为TXT文件。需求是导出的TXT文件需为CP1252编码,但实际生成的却是UTF-8编码。

读取XML文件的代码:

import xml.etree.ElementTree as ET

xml_file_path = path_files + xml_filename

tree = ET.parse(xml_file_path)
root = tree.getroot()

读取TXT文件的代码:

import csv
            
with open(txt_filename, 'r', encoding=('cp1252')) as f:
    reader = csv.reader(f, delimiter='\t')       
    list_results = list(tuple(line) for line in reader)

我已通过以下代码将无法用CP1252编码的字符替换为"?":

def filter_cp1252(text):
    try:
        encoded_text = text.encode('cp1252')
        return text
    except UnicodeEncodeError:
        text2= ''
        for nl, letter in enumerate(text):
            try:
                encoded_letter = letter.encode('cp1252')
                text2 = text2 + letter
            except:
                text2 = text2 + '?'
        return text2

该过滤逻辑已验证有效,我将数据存入列表后转为DataFrame,再通过以下代码导出:

df_import2.to_csv(output, header=None, index=None, sep='\t', mode ='w', encoding = 'cp1252')

但导出的文件仍为UTF-8编码,我也曾尝试先导出为Excel再重新导入pandas,问题依旧。

解决思路
  • 升级pandas版本:旧版pandas对encoding='cp1252'的处理可能存在兼容性bug,升级到最新稳定版后重试。
  • 绕开pandas的to_csv,手动写入:用Python内置文件操作直接控制编码逻辑,避免pandas自动调整编码:
    import csv
    
    with open(output, 'w', encoding='cp1252', newline='') as f:
        writer = csv.writer(f, delimiter='\t')
        # 遍历DataFrame每一行,确保内容都经过过滤
        for row in df_import2.itertuples(index=False):
            filtered_row = [filter_cp1252(str(col)) for col in row]
            writer.writerow(filtered_row)
    
  • 用工具准确检测文件编码:不要依赖系统文件查看器的编码判断,用chardet库验证实际编码:
    import chardet
    
    with open(output, 'rb') as f:
        detect_result = chardet.detect(f.read())
        print("文件实际编码:", detect_result['encoding'])
    
  • 确保DataFrame全列过滤:确认过滤函数应用到了DataFrame的所有文本列,避免遗漏未处理内容导致编码切换:
    # 批量处理DataFrame所有单元格
    df_import2 = df_import2.applymap(filter_cp1252)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 09:05:15