1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pythonで複数のCSVファイルを1ファイルに結合して保存する

Last updated at Posted at 2025-07-03

概要

仕事で頻繁に使っていたので備忘録的に
カラム名が全部一致しなくてもOK

A ファイル
ID time color
1001 1234 Red
1001 1235 Green
B ファイル
ID time color type
1002 1234 Purple SDN
1002 1235 Purple SDN
結合:Aファイル+Bファイル
ID time color type
1001 1234 Red
1001 1235 Green
1002 1234 Purple SDN
1002 1235 Purple SDN

環境

python3.x
jupyter lab

フォルダ構成

1_flow : Pythonファイル
2_data : csvファイルを入れる(これをまとめたい)
3_output : 結合したcsvファイルの出力先

image.png

コード

import os
import glob
import pandas as pd

#=============================================
# currentパス
#=============================================
current_dpath = os.getcwd()
#=============================================
# parentパス
#=============================================
parent_dpath =os.path.sep.join(current_dpath.split(os.path.sep)[:-1])

#=============================================
# Inputデータフォルダパス
#=============================================

INPUT_DNAME = "2_data"
input_dpath =os.path.sep.join([parent_dpath,INPUT_DNAME])

#=============================================
# 出力先のフォルダパス
#=============================================
OUTPUT_DNAME = "3_output"
output_dpath =os.path.sep.join([parent_dpath,OUTPUT_DNAME])

#=============================================
# 出力先のフォルダ なければ作成
#=============================================
os.makedirs(output_dpath,exist_ok = True)

#=============================================
# 出力先のフォルダ内の 前回処理ファイルを削除
#=============================================
dir = output_dpath
for f in os.listdir(dir):
    os.remove(os.path.join(dir, f))

#=============================================
# ファイルリスト
#=============================================
csv_files = glob.glob(input_dpath + "/*.csv")

#=============================================
# 保存名
#=============================================
save_name = "結合.csv"

data_list=[]
for file in csv_files:
    data_list.append(pd.read_csv(file))

data_df = pd.concat(data_list,axis=0)
data_df.to_csv(output_dpath + "/" + save_name, encoding='cp932',index =False)
#=============================================
# 保存フォルダ開く
#=============================================
os.startfile(os.path.realpath(output_dpath) + "\\")


保存ファイルを開く場合
ファイル容量が大きい場合はやめたほうが良いけど

#=============================================
# 保存したファイル開く
#=============================================
os.startfile(os.path.realpath(output_dpath) + "\\" + save_name)
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?