페싱코드 파이썬 코드

파이썬으로 오래된 파일 삭제하여 용량 관리하기

정과장하루살이 2025. 2. 22. 14:10
반응형

 

파이썬을 이용해서 오래된 파일을 삭제하는 코드입니다.

업무를 하다보면 정기적으로 쌓이는 파일들이 있는데,

일정 기간 이상 초과되면 삭제해주는 코드에요.

 

이것을 윈도우 스케줄러를 이용하면, 

정기적으로 실행하여 자동으로 용량관리를 할 수 있습니다.

 

좋은 하루 보내세요 !!!

import os
import time
from datetime import datetime, timedelta

# 특정 폴더 경로
folder_path = "/path/to/your/folder"

# 파일을 삭제할 기준 날짜 (예: 30일 이상된 파일)
days_threshold = 30
threshold_time = time.time() - (days_threshold * 86400)  # 86400초 = 1일

# 폴더 내 파일 목록 가져오기
for filename in os.listdir(folder_path):
    file_path = os.path.join(folder_path, filename)

    # 파일인지 디렉터리인지 확인
    if os.path.isfile(file_path):
        # 파일의 마지막 수정 시간을 확인
        file_mod_time = os.path.getmtime(file_path)

        # 파일이 기준 날짜를 초과했으면 삭제
        if file_mod_time < threshold_time:
            try:
                os.remove(file_path)
                print(f"파일 삭제됨: {filename}")
            except Exception as e:
                print(f"파일 삭제 실패: {filename}, 오류: {e}")

 

 

반응형