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

Python处理列数不一致的逗号分隔文本并写入Excel问题

解决文本文件转Excel(多工作表)及列数不匹配问题

单文件处理代码

你的问题出在pd.read_table按逗号拆分列时,每行的字段数不一致导致解析失败。换一种思路:把每行作为单个单元格内容处理,步骤如下:

import pandas as pd

# 读取文本文件内容
with open("exp.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()

# 处理每行:去除换行符、末尾逗号,将剩余逗号替换为空格
processed = [line.strip().rstrip(",").replace(",", " ") for line in lines]

# 转为单列DataFrame
df = pd.DataFrame(processed, columns=["内容"])

多文件批量生成Excel(每个文件对应一个工作表)

如果有多个文本文件,用pd.ExcelWriter批量写入,每个文件对应一个独立工作表:

import pandas as pd
import os

# 配置路径
txt_dir = "./你的文本文件目录"
output_path = "结果文件.xlsx"

# 批量处理并写入Excel
with pd.ExcelWriter(output_path) as writer:
    for file_name in os.listdir(txt_dir):
        if not file_name.endswith(".txt"):
            continue
        file_path = os.path.join(txt_dir, file_name)
        # 读取并处理文件
        with open(file_path, "r", encoding="utf-8") as f:
            lines = f.readlines()
        processed = [line.strip().rstrip(",").replace(",", " ") for line in lines]
        df = pd.DataFrame(processed, columns=["内容"])
        # 工作表名使用文件名(去掉后缀)
        sheet_name = os.path.splitext(file_name)[0]
        df.to_excel(writer, sheet_name=sheet_name, index=False)

关键说明

  • 原代码报错原因:pd.read_table指定delimiter=","时,会强制按逗号拆分出固定列数,当行与行之间的逗号数量不同时,拆分后的字段数不统一,触发解析错误。
  • 上述方法不拆分列,而是将每行内容处理为单个单元格的文本,完美匹配你想要的输出格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 19:16:12