Python

Python - Zipfile 한글 파일이름 깨짐 해결하기

올엠 2024. 3. 1. 21:38
반응형

Zipfile에서 압축을 해제한 파일의 한글깨짐이 발생하는데 이는 인코딩 문제이다.

이를 해결하기 위해서는 파일 이름 정보를 압축을 해제하기 전에 디코딩을 진행해야 한다.

아래 euc-kr 으로 디코딩을 하는 방식으로 파일에서 사용된 한글을 정상적으로 인식시킬 수 있다.

import zipfile

def extract_korean_zip(zip_path, extract_path):
  with zipfile.ZipFile(zip_path, 'r') as zip_ref:
    for zip_info in zip_ref.infolist():
      # 깨진 한글 파일 이름 복원
      filename = zip_info.filename.encode('cp437').decode('euc-kr')
      
      # 폴더 경로 처리
      if filename.endswith('/'):
        continue
      
      # 파일 압축 해제
      zip_ref.extract(zip_info, extract_path, filename)

  return True

# 예시
zip_path = '/path/to/your.zip'
extract_path = '/path/to/extract'

extract_korean_zip(zip_path, extract_path)

 

하지만 무조건 한글로 디코딩 하기 보다는 한글이 파일이름에 포함되었는지를 확인해서 진행하는 것을 추천한다.

import re

def is_korean_filename(filename):
  """
  파일 이름이 한글인지 체크합니다.

  Args:
    filename: 파일 이름

  Returns:
    파일 이름이 한글인 경우 True, 그렇지 않으면 False
  """

  pattern = re.compile('[가-힣]+')
  return pattern.match(filename) is not None
반응형