import csv
import os
base_folder_path = os.getcwd()
list_path = os.path.join(base_folder_path, "list")
# ディレクトリ名と絶対パスの対応を格納する辞書を初期化
path_dict = {}
# 指定したディレクトリ内のディレクトリのリストを取得し、辞書に追加
for item in os.listdir(list_path):
full_path = os.path.join(list_path, item)
if os.path.isdir(full_path):
path_dict[item] = full_path
# 新しいCSVファイルのパス
output_csv_path = "./output.csv"
# csvの読み込みと書き込み
with open("./data_list.csv", "r", encoding="utf-8-sig") as read_file, open(
output_csv_path, "w", encoding="utf-8-sig", newline=""
) as write_file:
reader = csv.reader(read_file, delimiter=",")
writer = csv.writer(write_file, delimiter=",")
for row in reader:
directory_name = row[0].strip()
if directory_name in path_dict:
directory_path = path_dict[directory_name]
row.append(directory_path) # 対応するディレクトリのパスを追加
writer.writerow(row) # 書きこみ
修正後↓
import csv
import os
import argparse
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("-l", "--list_path", default="./list")
parser.add_argument("-i", "--input_path", default="./data_list.csv")
parser.add_argument("-o", "--output_path", default="./output.csv")
args = parser.parse_args()
list_path = args.list_path
input_csv_path = args.input_path
output_csv_path = args.output_path
# ディレクトリ名と絶対パスの対応を格納する辞書を初期化
path_dict = {}
# 指定したディレクトリ内のディレクトリのリストを取得し、辞書に追加
for item in os.listdir(list_path):
full_path = os.path.join(list_path, item)
if os.path.isdir(full_path):
path_dict[item] = full_path
itemlist_with_added_path = []
# csvの読み込み
with open(input_csv_path, "r", encoding="utf-8-sig") as read_file:
reader = csv.reader(read_file, delimiter=",")
for data in reader:
directory_name = data[0].strip()
if directory_name in path_dict:
directory_path = path_dict[directory_name]
data.append(directory_path) # 対応するディレクトリのパスを追加
itemlist_with_added_path.append(data)
with open(output_csv_path, "w", encoding="utf-8-sig", newline="") as write_file:
writer = csv.writer(write_file, delimiter=",")
for data in itemlist_with_added_path:
writer.writerow(data) # 書きこみ
if __name__ == "__main__":
main()
追加↓
from openpyxl import Workbook
output_data = {"hoge1": [["1", "a"], ["2", "b"]], "hoge2": [["3", "c"], ["4", "d"]]}
wb = Workbook()
ws = wb.active
row = 0
for path, error_data_list in output_data.items():
for error_data in error_data_list:
for column, data in enumerate([path] + error_data):
ws.cell(row + 1, column + 1, data)
row += 1
wb.save("sample.xlsx")