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

如何在Pandas中合并多个TXT文件并添加文件名作为新列

解决方案

方法1:Shell命令(Linux/macOS环境)

类Unix系统下可直接用命令快速完成合并与格式化:

基础快速版

echo "Samplename   value1       value2       value3       value4" > merged_result.txt && awk '{print FILENAME "\t" $0}' {1..65}.txt >> merged_result.txt

列对齐美观版

如果需要更整齐的排版,用printf控制列宽:

echo -e "Samplename   value1       value2       value3       value4" > merged_result.txt && awk '{printf "%-10s %-12s %-12s %-12s %-12s\n", FILENAME, $1, $2, $3, $4}' {1..65}.txt >> merged_result.txt

说明:

  • 先将表头写入结果文件merged_result.txt
  • awk自动遍历1-65号txt文件,通过FILENAME获取当前文件名,与每行内容拼接后追加到结果文件
  • %-10s这类格式表示左对齐、固定宽度的字符串,确保列对齐整齐

方法2:Python脚本(跨平台通用)

适合Windows或不熟悉Shell的用户,创建如下脚本:

# 定义输出表头
header = "Samplename   value1       value2       value3       value4"

# 打开结果文件写入
with open("merged_result.txt", "w", encoding="utf-8") as out_file:
    out_file.write(header + "\n")
    
    # 遍历1到65号文件
    for file_num in range(1, 66):
        file_name = f"{file_num}.txt"
        try:
            with open(file_name, "r", encoding="utf-8") as in_file:
                for line in in_file:
                    line_content = line.strip()
                    # 跳过空行
                    if not line_content:
                        continue
                    # 格式化每行,保证文件名列宽度一致
                    formatted_line = f"{file_name:<10} {line_content}"
                    out_file.write(formatted_line + "\n")
        except FileNotFoundError:
            print(f"⚠️ 文件 {file_name} 不存在,已跳过")

运行方式

在命令行执行:

python merge_files.py

说明:

  • 自动跳过文件中的空行
  • 若某个编号的文件不存在,会打印警告并继续处理其他文件
  • 兼容Windows、Linux、macOS全平台

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:39:18