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

使用Python合并多个txt表格文件时保留唯一表头的方法

合并多表头TXT文件并去除重复表头

问题分析

原代码直接将每个TXT文件的所有内容逐行写入输出文件,导致每个文件的表头(Sales、Purchase)重复出现,不符合仅保留一个表头的需求。以下提供两种可支持新增文件的解决方案:


方案一:纯Python文件操作(无需依赖第三方库)

核心逻辑:写入第一个文件的完整内容(包含表头),后续文件跳过第一行(表头)仅写入数据行。

import glob

file_names = glob.glob("./*.txt")
with open('output_file.txt', 'w') as out_file:
    # 处理第一个文件,写入完整内容(含表头)
    if file_names:
        with open(file_names[0]) as first_file:
            out_file.write(first_file.read())
        # 处理剩余文件,跳过第一行表头
        for file in file_names[1:]:
            with open(file) as in_file:
                next(in_file)  # 跳过表头行
                out_file.write(in_file.read())

方案二:使用Pandas实现(更简洁,适合有数据处理需求的场景)

利用Pandas读取每个文件时自动识别表头,合并后仅保留一组表头,最后统一输出。

import pandas as pd
import glob

file_names = glob.glob("./*.txt")
# 读取所有文件并合并,header=0指定第一行为表头
df_list = [pd.read_csv(file, delimiter='/') for file in file_names]
merged_df = pd.concat(df_list, ignore_index=True)
# 保存合并后的文件,index=False避免写入行索引
merged_df.to_csv('output_file.txt', sep='/', index=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 00:52:04