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

如何用Python遍历多文件夹并给CSV文件添加表头

遍历多文件夹为CSV文件添加表头的Python实现

核心思路

  • 递归遍历指定根目录下的所有子文件夹,筛选出所有CSV文件
  • 读取每个CSV的原有内容,在开头插入自定义表头后重新写入
  • 可选:跳过已包含目标表头的文件,避免重复操作

基础实现代码

import pathlib
import csv

# 自定义表头,根据实际需求修改列名
TARGET_HEADERS = ["用户ID", "姓名", "注册时间", "消费金额"]
# 替换为你的根文件夹路径(绝对路径/相对路径均可)
ROOT_FOLDER = pathlib.Path("./your_root_folder")

# 递归遍历所有子文件夹中的CSV文件
for csv_file in ROOT_FOLDER.rglob("*.csv"):
    # 读取文件所有内容
    with open(csv_file, "r", newline="", encoding="utf-8") as in_file:
        csv_reader = csv.reader(in_file)
        content_rows = list(csv_reader)
    
    # 写入带表头的内容
    with open(csv_file, "w", newline="", encoding="utf-8") as out_file:
        csv_writer = csv.writer(out_file)
        csv_writer.writerow(TARGET_HEADERS)
        csv_writer.writerows(content_rows)
    
    print(f"已完成:{csv_file.resolve()}")

关键细节说明

  • pathlib.Path.rglob("*.csv"):自动递归遍历所有嵌套子文件夹,精准匹配.csv后缀文件,比传统os.walk写法更简洁直观
  • 使用csv模块处理文件:避免手动处理逗号分隔、换行符等格式问题,兼容性更强
  • 编码设置:默认用utf-8,如果你的CSV文件是GBK等其他编码,需要修改encoding参数

进阶优化:跳过已有表头的文件

如果部分CSV已经包含目标表头,可以添加判断逻辑避免重复操作:

import pathlib
import csv

TARGET_HEADERS = ["用户ID", "姓名", "注册时间", "消费金额"]
ROOT_FOLDER = pathlib.Path("./your_root_folder")

for csv_file in ROOT_FOLDER.rglob("*.csv"):
    with open(csv_file, "r", newline="", encoding="utf-8") as in_file:
        csv_reader = csv.reader(in_file)
        content_rows = list(csv_reader)
    
    # 检查第一行是否已为目标表头
    if content_rows and content_rows[0] == TARGET_HEADERS:
        print(f"已跳过(表头已存在):{csv_file.resolve()}")
        continue
    
    # 写入更新后的内容
    with open(csv_file, "w", newline="", encoding="utf-8") as out_file:
        csv_writer = csv.writer(out_file)
        csv_writer.writerow(TARGET_HEADERS)
        csv_writer.writerows(content_rows)
    
    print(f"已完成:{csv_file.resolve()}")

注意事项

  • 操作前务必备份原始文件:避免代码逻辑错误或编码不匹配导致数据丢失
  • 处理大体积CSV:如果文件过大,不要一次性读取所有行到内存,可改用临时文件中转,边读边写
  • 分隔符适配:如果CSV用制表符或其他分隔符,初始化csv.reader和csv.writer时添加delimiter="\t"参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 03:21:03