0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CSV:ヘッダー変換(Python)

Last updated at Posted at 2025-03-19
import csv

def replace_csv_header(input_file: str, output_file: str, header_mapping: dict):
    """
    CSVファイルのヘッダーを指定したマッピングに基づいて置き換える関数

    :param input_file: 元のCSVファイル名
    :param output_file: 変更後のCSVファイル名
    :param header_mapping: {元のヘッダー名: 置換後のヘッダー名} の辞書
    """
    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} に保存しました。")

# 使い方
header_mapping = {
    "user1": "田中",
    "user2": "ジョン",
    "user3": "サミー"
}

replace_csv_header("input.csv", "output.csv", header_mapping)

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")
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?