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

Python读取多文件夹txt生成DataFrame时编码错误求助

解决UnicodeDecodeError编码问题

出现这个错误的原因是chardet检测出的编码(此处为cp949)无法解码文件中的部分字节,可能是编码检测不准确,或是文件本身存在损坏的字节序列。可以通过以下方案解决:

核心解决要点

  • 为chardet检测失败的场景设置备用编码(如utf-8)
  • 读取文件时添加错误处理策略,避免个别错误字节导致整个读取流程中断
  • 重构代码减少重复逻辑,提升可维护性

修改后的完整代码

import os
import pandas as pd
import chardet

def load_files_from_folder(folder_path, label):
    ids = []
    words = []
    labels = []
    for filename in os.listdir(folder_path):
        file_full_path = os.path.join(folder_path, filename)
        # 跳过文件夹中的非文件项(比如子目录)
        if not os.path.isfile(file_full_path):
            continue
        # 检测文件编码
        with open(file_full_path, "rb") as f:
            result = chardet.detect(f.read())
            # 检测失败时用utf-8作为备用编码
            encoding = result["encoding"] or "utf-8"
        # 读取文件并处理解码错误
        try:
            with open(file_full_path, "r", encoding=encoding, errors="replace") as f:
                word_content = f.read()
                ids.append(filename)
                words.append(word_content)
                labels.append(label)
        except Exception as e:
            print(f"读取文件 {filename} 失败: {str(e)}")
            continue
    return ids, words, labels

# 加载两个文件夹的数据
good_ids, good_words, good_labels = load_files_from_folder("myfolder/good", "good")
bad_ids, bad_words, bad_labels = load_files_from_folder("myfolder/bad", "bad")

# 合并数据并创建DataFrame
all_ids = good_ids + bad_ids
all_words = good_words + bad_words
all_labels = good_labels + bad_labels

df = pd.DataFrame({"Id": all_ids, "word": all_words, "label": all_labels})

关键改动说明

  • 错误处理参数:errors="replace"会将无法解码的字节替换为�,避免直接抛出错误;也可根据需求使用errors="ignore"直接忽略错误字节
  • 备用编码:当chardet检测返回None时,自动使用utf-8作为备选编码
  • 跳过非文件项:避免读取文件夹中的子目录导致异常
  • 异常捕获:捕获单个文件的读取异常,不影响其他文件的处理,同时打印错误信息方便排查

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 16:52:35