본문 바로가기
Programming/Python

[Python] csv 파일을 목록화하고 폴더 생성후 파일 저장하기

by goatlab 2023. 5. 15.
728x90
반응형
SMALL

csv 파일을 목록화하고 폴더 생성후 파일 저장하기

 

import os
import matplotlib.pyplot as plt

# csv 파일 목록 가져오기
csv_files = os.listdir(".")

for csv_file in csv_files:
    # csv 파일 이름으로 폴더 만들기
    folder_name = os.path.splitext(csv_file)[0]
    try:
        os.mkdir(folder_name)
    except FileExistsError:
        pass

    # csv 파일을 폴더에 저장
    with open(csv_file, "r") as csv_file:
        data = csv_file.read()

    # 이미지를 폴더에 저장
    plt.plot(data)
    plt.savefig(os.path.join(folder_name, csv_file + ".png"))
    plt.clf()

 

각 csv 파일의 이름으로 폴더가 생성되고 csv 파일의 데이터를 나타내는 이미지가 해당 폴더에 저장된다. 이미지 이름은 csv 파일 이름과 ".png" 확장자로 구성된다. 폴더가 이미 존재하는 경우 오류가 발생하지 않고 넘어간다.

 

728x90
반응형
LIST