0
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?

複数のCSVファイルに対して、同一アイテムの数値を加算する

Posted at

import argparse
import csv
import os


def main() -> None:

    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--input_dir_path", default="./")
    parser.add_argument("-o", "--output_file_path", default="./output.csv")
    args = parser.parse_args()

    input_dir_path = args.input_dir_path
    output_file_path = args.output_file_path

    csv_files = [file for file in os.listdir(input_dir_path) if file.endswith(".csv")]
    margede_data = {}

    # csvの読み込み
    for csv_file in csv_files:
        with open(csv_file, "r", encoding="utf-8") as read_file:
            reader = csv.reader(read_file, delimiter=",")

            for data in reader:
                if data[0] in margede_data:
                    margede_data[data[0]] += int(data[1])
                else:
                    margede_data[data[0]] = int(data[1])

    # マージ後データのcsv出力
    with open(output_file_path, "w", encoding="utf-8", newline="") as write_file:
        writer = csv.writer(write_file, delimiter=",")

        for jancode, sales_volume in margede_data.items():
            writer.writerow([jancode, sales_volume])


if __name__ == "__main__":
    main()
0
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
0
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?