파이썬을 활용한 압축 파일 일괄 해제 도구

이 스크립트는 현재 폴더 내 모든 .zip 파일을 자동으로 해제하는 간편한 도구입니다. 배치 파일과 함께 사용하면, 단일 폴더에 있는 압축 파일을 한 번에 처리할 수 있어 매우 효율적입니다.

기본 동작 원리

스크립트는 현재 작업 디렉터리의 모든 파일을 순회하며, 확장자가 .zip인 파일만 대상으로 합니다. 이후 각 파일을 zipfile 모듈로 열어 내부 콘텐츠를 분석하고, 적절한 위치에 해제합니다.

처리 로직 세부 사항

압축 파일 내부 구조에 따라 다음 세 가지 경우를 구분하여 처리합니다:

  1. 하나의 폴더만 포함된 경우: 폴더 이름이 압축 파일 이름과 다를 경우, 해제 후 이름을 맞춤.
  2. 여러 개의 파일 또는 하위 폴더가 혼합된 경우: 전체 내용을 [압축파일명]이라는 새로운 폴더에 저장.
  3. 압축 파일 자체가 단일 파일인 경우: 그대로 현재 폴더에 추출.

코드 예시

import os
from zipfile import ZipFile

current_dir = os.getcwd()

for file_name in os.listdir(current_dir):
    if not file_name.endswith('.zip'):
        continue

    zip_path = os.path.join(current_dir, file_name)
    archive = ZipFile(zip_path, 'r')

    # 압축 파일 내 항목 목록
    contents = archive.namelist()
    if not contents:
        archive.close()
        continue

    # 첫 번째 항목 기준으로 구조 판단
    first_item = contents[0]
    is_single_folder = True

    for item in contents[1:]:
        if not item.startswith(first_item):
            is_single_folder = False
            break

    # 해제 경로 결정
    extract_path = current_dir if is_single_folder else os.path.join(current_dir, file_name[:-4])

    # 압축 해제
    for item in contents:
        archive.extract(item, extract_path)

    # 폴더 이름 재정의 (만약 이름이 다르고 하나의 폴더라면)
    if is_single_folder and first_item.rstrip('/') != file_name[:-4]:
        extracted_folder = first_item.rstrip('/')
        target_folder = os.path.join(current_dir, file_name[:-4])
        if os.path.exists(extracted_folder) and not os.path.exists(target_folder):
            os.rename(extracted_folder, target_folder)

    archive.close()

배포 방법

스크립트를 unzip_batch.py로 저장한 후, 다음과 같은 명령어를 포함하는 run_unzip.bat 파일을 생성하세요:

python unzip_batch.py

이 배치 파일을 압축 파일들이 포함된 폴더에 넣은 후 실행하면, 모든 .zip 파일이 자동으로 해제됩니다.

향후 확장성 고려

현재 코드는 .zip 형식에 한정되어 있지만, .7z, .rar 등의 형식도 필요하다면 py7zr 또는 외부 라이브러리를 통한 시스템 호출 방식으로 확장할 수 있습니다. 다만, 복잡한 종속성 관리는 피하기 위해 기본적으로는 내장된 zipfile을 우선적으로 활용하는 것이 좋습니다.

태그: python zipfile batch script automation compression

6월 20일 01:01에 게시됨