[Python] zip파일 풀기(zipfile)

Hyun·2022년 7월 26일
0

Python

목록 보기
2/3

zipfile docs 바로가기

Python zip파일 풀기

zip 파일 풀기

import zipfile
from zipfile import ZipFile

with zipfile.ZipFile(zip_file_path, 'r') as obj:
	obj.namelist()		# zip파일 내의 파일 이름을 가진 list 반환
    obj.extract(filename, directory_name)    # directory 내에 압축 해제
    obj.extractall(directory_name)    # directory 내에 압축 해제(없으면 생성)
  • zipfile.ZipFile : zip file 가져오기(as obj : with 구문 내에서만 작동하는 obj 변수에 저장하기)
    • zip_file_path : zip파일이 저장되어 있는 경로
    • file : file 경로
    • mode : 'r'(읽기, default), 'w'(쓰기), 'a'(append, 수정), 'x'(새 파일을 독점적으로 작성하고 쓰기)
  • namelist() : file's name list 반환
  • extract(fileName, path) : 경로(디렉토리 생성 가능)에 해당 파일 압축 해제
  • extractall(fileName, path) : 경로(디렉토리 생성 가능)에 압축 해제

압축을 풀지 않고 읽기

  • 작업 디렉토리 메모리가 부족할 때 사용!
  • open, read로 가능하다.
with zipfile.ZipFile(zip_file_path, 'r') as obj:
    zip_namelist = obj.namelist()
    
    for name in zip_namelist :
      readed = obj.open(name)		# binary 형태로 읽기
      
      if name.endswith('.csv') :   # csv파일은 2가지
        df = pd.read_csv(readed)
      # 혹은 readed = obj.read(name); pd.read_csv(BytesIO(readed))
      
      elif name.endswith('.png') :		# Image 형태로 읽기
        img = Image.open(readed)
        img = img.resize((224, 224))
        img_arr = np.array(img)
        arr = np.append(arr, img_arr)		# json 형태 읽기
        
      elif name.endswith('json') :  # json
        js = json.load(readed)
        length = len(js['annotations'])
  • open(name) : zip파일 내 바이너리 파일로 열기, with ~ open 가능
  • read(name) : 파일 name의 byte 열 반환

참조

[Python] 압축 파일(zip) 다루기 (ft. 압축 풀지 않고 데이터 읽기)
출처: https://gmnam.tistory.com/256 [Voyager:티스토리], voyager

zipfile docs

0개의 댓글