从多子目录复制多CSV文件并合并为单个CSV的技术问题
解决方案:批量复制并合并CSV文件
步骤1:批量复制目标CSV文件
先遍历所有day*子目录,定位每个目录下weather文件夹中的weather*.csv文件,将其复制到Sessions/Weather目录(目录不存在则自动创建):
import os import shutil # 父目录路径 root_dir = "/Sessions" # 目标存储目录 target_dir = os.path.join(root_dir, "Weather") # 创建目标目录(已存在则跳过) os.makedirs(target_dir, exist_ok=True) # 遍历父目录下所有层级 for dirpath, _, filenames in os.walk(root_dir): # 筛选出day*/weather格式的目录 parent_dir = os.path.basename(os.path.dirname(dirpath)) if parent_dir.startswith("day") and os.path.basename(dirpath) == "weather": # 匹配当前目录下的weather*.csv文件 for file in filenames: if file.startswith("weather") and file.endswith(".csv"): src_file = os.path.join(dirpath, file) dst_file = os.path.join(target_dir, file) shutil.copy(src_file, dst_file) print(f"复制完成:{src_file} -> {dst_file}")
步骤2:合并所有CSV文件到weather_All.csv
完成复制后,合并目标目录下的所有CSV文件,修正原代码的路径问题并增加容错处理:
import pandas as pd import glob # 目标目录路径 target_dir = "/Sessions/Weather" # 获取目录下所有weather开头的CSV文件 all_filenames = glob.glob(os.path.join(target_dir, "weather*.csv")) # 批量读取文件并收集数据框 df_collection = [] for file in all_filenames: try: df = pd.read_csv(file) df_collection.append(df) print(f"读取成功:{file}") except Exception as e: print(f"读取失败 {file}:{str(e)}") # 合并数据,重置索引并保留原列顺序 combined_df = pd.concat(df_collection, ignore_index=True, sort=False) # 导出合并后的文件 output_file = os.path.join(target_dir, "weather_All.csv") combined_df.to_csv(output_file, index=False, encoding='utf-8-sig') print(f"合并完成,文件已保存:{output_file}")
关键说明
- 复制阶段:通过
os.walk精准定位目标文件路径,避免误复制无关文件;os.makedirs的exist_ok=True参数确保目录创建逻辑更健壮。 - 合并阶段:增加异常处理捕获文件读取错误,
concat的ignore_index=True重置合并后的索引,sort=False避免自动调整列顺序。
内容的提问来源于stack exchange,提问作者tygarn
相关产品推荐
相关产品推荐

