ファイル結合は「分割されたデータを元の形に戻す」ための基本操作
業務自動化では、巨大ファイルを分割して扱った後、最終的に元のファイルへ戻す処理(結合)が必要になる場面が多くあります。
特に次のようなケースで役立ちます。
- 分割されたログファイルを一つにまとめたい
- CSV を複数に分割して処理した後、再度結合したい
- バイナリファイル(ZIP・動画・画像など)を分割して転送した後に復元したい
Python では、テキスト・CSV・バイナリなど、どんな形式でも安全に結合できます。
ここでは、初心者でも理解しやすいように、基本から実務テンプレートまで丁寧に解説します。
テキストファイルを順番に結合する基本
最小構成:複数のテキストを一つにまとめる
def merge_text(files, output):
with open(output, "w", encoding="utf-8") as dst:
for f in files:
with open(f, "r", encoding="utf-8") as src:
dst.write(src.read())
merge_text(["part1.txt", "part2.txt", "part3.txt"], "merged.txt")
Python重要ポイント
dst.write(src.read())で内容をそのまま追加- テキストは「行」という概念があるため、結合は非常に簡単
- ファイル順序が重要なので、リストの順番がそのまま反映される
CSV をヘッダー付きで結合する(実務で最も重要)
複数 CSV を「ヘッダーは最初の1回だけ」書いて結合する
def merge_csv(files, output):
with open(output, "w", encoding="utf-8") as dst:
header_written = False
for f in files:
with open(f, "r", encoding="utf-8") as src:
header = src.readline()
if not header_written:
dst.write(header)
header_written = True
for line in src:
dst.write(line)
merge_csv(["data_1.csv", "data_2.csv", "data_3.csv"], "merged.csv")
Python深掘りポイント
- CSV はヘッダーが重複すると壊れるため、最初の1回だけ書く
- 2つ目以降のファイルはヘッダーを読み飛ばす
- 分割 → 処理 → 結合という業務フローで必須のパターン
バイナリファイル(ZIP・動画・画像)を安全に結合する
バイナリは「行」ではなく「バイト」で結合する
def merge_binary(files, output):
with open(output, "wb") as dst:
for f in files:
with open(f, "rb") as src:
dst.write(src.read())
merge_binary(["movie.mp4_1", "movie.mp4_2", "movie.mp4_3"], "movie.mp4")
Python深掘りポイント
- バイナリは必ず
rb/wbで扱う - 分割時と同じ順番で結合しないと壊れる
- ZIP・動画・画像など、どんな形式でも復元可能
フォルダ内の分割ファイルを自動で並べて結合する
例:bigfile.txt_1, bigfile.txt_2, … を自動で結合
import os
import re
def merge_auto(folder, prefix, output):
files = []
for name in os.listdir(folder):
m = re.match(rf"{prefix}_(\d+)", name)
if m:
index = int(m.group(1))
files.append((index, os.path.join(folder, name)))
files.sort(key=lambda x: x[0])
with open(output, "wb") as dst:
for _, path in files:
with open(path, "rb") as src:
dst.write(src.read())
merge_auto("parts", "bigfile.txt", "bigfile.txt")
Python深掘りポイント
- 正規表現で番号を抽出し、番号順にソート
- 分割ファイルが多い場合でも自動で順番を整えて結合
- バイナリモードで開くことでどんな形式にも対応
行数分割したファイルを結合するテンプレート
分割ファイルを順番に結合するだけで元に戻る
def merge_line_split(prefix, count, output):
with open(output, "w", encoding="utf-8") as dst:
for i in range(1, count + 1):
part = f"{prefix}_{i}.txt"
with open(part, "r", encoding="utf-8") as src:
dst.write(src.read())
merge_line_split("bigfile.txt", 5, "bigfile_merged.txt")
Python深掘りポイント
- 分割時に連番を付けていれば結合は非常に簡単
- 行数分割 → 結合はログ処理でよく使う
pathlib を使った読みやすい結合コード
Path オブジェクトで直感的に書ける
from pathlib import Path
def merge_path(files, output):
dst = Path(output)
with dst.open("wb") as w:
for f in files:
p = Path(f)
with p.open("rb") as r:
w.write(r.read())
merge_path(["part1.bin", "part2.bin"], "merged.bin")
Pythonメリット
/でパス結合できるPath.open()が読みやすい- バイナリ・テキストどちらにも対応
ファイル結合を業務で使うときの重要ポイント
- テキストは
utf-8、バイナリはrb/wbを使う - CSV はヘッダーを重複させない
- 分割時と同じ順番で結合しないと壊れる
- 自動化する場合はファイル名の規則(連番・日付)を統一する
- 結合後に ZIP/TAR 圧縮と組み合わせるとさらに便利
