본문 바로가기

Study Information Technology

자동화된 파일 정리 및 클린업 스크립트 작성하기

728x90
반응형

자동화된 파일 정리 및 클린업 스크립트 작성하기

Overview

파일 정리 및 클린업을 자동화하는 스크립트를 작성하는 것은 파일 관리 작업을 효율적으로 처리하는 데 도움이 됩니다. Python의 osshutil 모듈을 사용하면 이러한 작업을 쉽게 수행할 수 있습니다. 이 스크립트는 디렉토리 내의 파일을 유형별로 분류하고, 필요 없는 파일을 삭제하는 등의 작업을 자동으로 처리합니다.

이 문서에서는 osshutil 모듈을 활용하여 파일을 정리하고 클린업하는 스크립트를 작성하는 방법을 자세히 설명하겠습니다. 여기서는 디렉토리 구조를 관리하고, 파일을 이동하거나 삭제하는 기본적인 기능부터 시작해 고급 기능까지 다룰 것입니다.

1. 기본 모듈 소개

os 모듈

os 모듈은 운영 체제와 상호작용하는 다양한 기능을 제공합니다. 디렉토리와 파일을 생성, 삭제, 탐색할 수 있는 기능을 포함하고 있습니다.

  • os.listdir(path): 지정된 경로의 디렉토리 내 파일과 서브디렉토리 목록을 반환합니다.
  • os.path.join(path, *paths): 여러 경로를 하나로 결합합니다.
  • os.makedirs(path, exist_ok=False): 디렉토리 생성. exist_okTrue로 설정하면 이미 존재하는 디렉토리에 대해 에러가 발생하지 않습니다.

shutil 모듈

shutil 모듈은 고급 파일 작업을 지원합니다. 파일 복사, 이동, 압축 및 디렉토리 복사 등을 처리할 수 있습니다.

  • shutil.copy(src, dst): src 파일을 dst로 복사합니다.
  • shutil.move(src, dst): src 파일이나 디렉토리를 dst로 이동합니다.
  • shutil.rmtree(path): path 디렉토리를 재귀적으로 삭제합니다.

2. 파일 정리 및 클린업 스크립트 작성하기

2.1. 기본 디렉토리 구조 설정

먼저, 작업할 디렉토리와 파일 구조를 설정합니다. 예를 들어, 다운로드 폴더를 정리한다고 가정하겠습니다.

import os
import shutil

def setup_directories(base_path):
# 필요한 디렉토리 생성
os.makedirs(os.path.join(base_path, 'Images'), exist_ok=True)
os.makedirs(os.path.join(base_path, 'Documents'), exist_ok=True)
os.makedirs(os.path.join(base_path, 'Videos'), exist_ok=True)
os.makedirs(os.path.join(base_path, 'Archives'), exist_ok=True)
print("디렉토리 구조가 설정되었습니다.")

base_path = '/path/to/your/downloads'
setup_directories(base_path)

이 코드는 base_path에 필요한 하위 디렉토리를 생성합니다. os.makedirsexist_ok=True는 이미 디렉토리가 존재할 경우 에러를 발생시키지 않습니다.

2.2. 파일 이동 및 정리

다음으로, 파일 유형에 따라 파일을 해당 디렉토리로 이동합니다.

def move_files(base_path):
# 파일 유형별 디렉토리 경로
image_extensions = ('.png', '.jpg', '.jpeg', '.gif')
document_extensions = ('.pdf', '.docx', '.txt', '.pptx')
video_extensions = ('.mp4', '.mov', '.avi')
archive_extensions = ('.zip', '.tar', '.gz', '.rar')

# 파일 목록 가져오기
files = os.listdir(base_path)

for file in files:
file_path = os.path.join(base_path, file)
if os.path.isfile(file_path):
ext = os.path.splitext(file)[1].lower()

if ext in image_extensions:
shutil.move(file_path, os.path.join(base_path, 'Images', file))
elif ext in document_extensions:
shutil.move(file_path, os.path.join(base_path, 'Documents', file))
elif ext in video_extensions:
shutil.move(file_path, os.path.join(base_path, 'Videos', file))
elif ext in archive_extensions:
shutil.move(file_path, os.path.join(base_path, 'Archives', file))
else:
print(f"{file}는 처리되지 않았습니다.")

print("파일 이동이 완료되었습니다.")

base_path = '/path/to/your/downloads'
move_files(base_path)

이 코드는 파일의 확장자를 검사하여 적절한 디렉토리로 이동합니다. 확장자 목록은 원하는 유형에 맞게 수정할 수 있습니다.

2.3. 불필요한 파일 삭제

특정 파일 유형을 삭제하는 기능도 추가할 수 있습니다. 예를 들어, 임시 파일이나 특정 패턴의 파일을 삭제할 수 있습니다.

def delete_temp_files(base_path):
temp_extensions = ('.tmp', '.bak', '.swp')

files = os.listdir(base_path)

for file in files:
file_path = os.path.join(base_path, file)
if os.path.isfile(file_path):
ext = os.path.splitext(file)[1].lower()

if ext in temp_extensions:
os.remove(file_path)
print(f"{file}이 삭제되었습니다.")

print("임시 파일 삭제가 완료되었습니다.")

base_path = '/path/to/your/downloads'
delete_temp_files(base_path)

이 코드는 .tmp, .bak, .swp 확장자를 가진 파일을 삭제합니다. 삭제하려는 파일 유형에 맞게 temp_extensions를 조정하세요.

3. 예외 처리 및 에러 대응

스크립트 실행 중 예상치 못한 문제가 발생할 수 있습니다. 예를 들어, 권한이 없는 파일에 접근하려 할 때 에러가 발생할 수 있습니다. 이를 처리하기 위해 try-except 블록을 사용할 수 있습니다.

def safe_move_file(src, dst):
try:
shutil.move(src, dst)
print(f"{src} -> {dst} 이동 완료")
except PermissionError:
print(f"권한 오류: {src}를 이동할 수 없습니다.")
except FileNotFoundError:
print(f"파일 없음: {src}를 찾을 수 없습니다.")
except Exception as e:
print(f"예상치 못한 오류 발생: {e}")

def move_files(base_path):
# 파일 유형별 디렉토리 경로
image_extensions = ('.png', '.jpg', '.jpeg', '.gif')
document_extensions = ('.pdf', '.docx', '.txt', '.pptx')
video_extensions = ('.mp4', '.mov', '.avi')
archive_extensions = ('.zip', '.tar', '.gz', '.rar')

files = os.listdir(base_path)

for file in files:
file_path = os.path.join(base_path, file)
if os.path.isfile(file_path):
ext = os.path.splitext(file)[1].lower()

if ext in image_extensions:
safe_move_file(file_path, os.path.join(base_path, 'Images', file))
elif ext in document_extensions:
safe_move_file(file_path, os.path.join(base_path, 'Documents', file))
elif ext in video_extensions:
safe_move_file(file_path, os.path.join(base_path, 'Videos', file))
elif ext in archive_extensions:
safe_move_file(file_path, os.path.join(base_path, 'Archives', file))
else:
print(f"{file}는 처리되지 않았습니다.")

print("파일 이동이 완료되었습니다.")

이 코드 블록은 파일 이동 시 발생할 수 있는 다양한 오류를 처리합니다. 사용자 권한 문제나 파일이 존재하지 않는 경우 등 여러 상황을 대비할 수 있습니다.

참고문서

이 문서와 코드를 통해 파일 정리 및 클린업 작업을 자동화할 수 있습니다. 각 기능을 조합하여 필요에 맞는 파일 관리 시스템을 구축해보세요.

728x90
반응형