import csv
def load_header_mapping(mapping_file: str) -> dict:
"""
ヘッダーの置き換えマッピングをCSVファイルから読み込む関数
:param mapping_file: Key-Value形式のCSVファイル (ヘッダーなし)
:return: {元のヘッダー名: 置換後のヘッダー名} の辞書
"""
mapping = {}
with open(mapping_file, mode="r", newline="", encoding="utf-8") as file:
reader = csv.reader(file)
for row in reader:
if len(row) == 2: # 正しいKey-Value形式のみ取得
mapping[row[0]] = row[1]
return mapping
def replace_csv_header(input_file: str, output_file: str, mapping_file: str):
"""
CSVファイルのヘッダーを指定したマッピングに基づいて置き換える関数
:param input_file: 元のCSVファイル名
:param output_file: 変更後のCSVファイル名
:param mapping_file: Key-Value形式のヘッダー対応表(CSVファイル)
"""
header_mapping = load_header_mapping(mapping_file)
with open(input_file, mode="r", newline="", encoding="utf-8") as infile, \
open(output_file, mode="w", newline="", encoding="utf-8") as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
# ヘッダーの変換
header = next(reader)
new_header = [header_mapping.get(col, col) for col in header] # マッピングに基づいて置換
writer.writerow(new_header)
# 残りのデータを書き込む
writer.writerows(reader)
print(f"ヘッダーを変更したCSVを {output_file} に保存しました。")
# 使い方
replace_csv_header("input.csv", "output.csv", "header_mapping.csv")