[Python] 압축파일 처리/zipfile 모듈


zipfile 모듈이란?

파일을 압축하거나 해제하는 등 압축파일에 관련된 모듈입니다. zipfile 모듈은 기본으로 설치되어 있는 파이썬 내장 라이브러리이기 때문에 따로 설치할 필요가 없습니다.


파일 하나만 압축

파일을 압축할 때는 write()를 사용합니다. 일단 os 모듈을 통해 작업할 위치로 현재 디렉토리를 변경해줍니다.

import zipfile, os
os.chdir('D:\\python_study\\zipfile_test') #현재 디렉토리 위치 변경

#파일 하나만 압축
one_new_zip = zipfile.ZipFile('new.zip','w')
one_new_zip.write('hello.txt')
one_new_zip.close()

 

파일 압축 전
파일 하나 압축 후


파일 여러개 압축

파일을 여러 개 압축할 때는 먼저 압축하고자하는 파일명을 리스트로 만들어 줍니다. 그리고 with 구문과 for문을 사용하여 반복문을 통해 압축합니다.

#파일 여러개 압축
file_list = ['data_green.png','hello.txt','programmer_pink.png']
with zipfile.ZipFile('multi_new.zip','w') as multi_new_zip:
    for i in file_list:
        multi_new_zip.write(i)

 

파일 여러개 압축 후


파일 압축풀기

압축을 풀 때는 하나의 파일만 압축을 푸는 extract(파일이름)과 전체파일을 푸는 extractall()이 있습니다.

#extract(파일이름) 해당 파일만 압축풀기
one_zip_out = zipfile.ZipFile('multi_new.zip')
one_zip_out.extract('hello.txt')
one_zip_out.close()

 

압축 풀기 전
파일 하나만 압축 해제 후

#extractall() 현재 디렉토리에 전체파일 압축풀기
multi_zip_out = zipfile.ZipFile('multi_new.zip')
multi_zip_out.extractall()
multi_zip_out.close()

 

전체 파일 압축 해제 후


namelist()

namelist()는 압축파일 내 파일명 즉, 목록을 읽어오는 함수입니다.

exZip = zipfile.ZipFile('multi_new.zip')
print(exZip.namelist())

#출력값
#['data_green.png', 'hello.txt', 'programmer_pink.png']

getinfo()

getinfo()는 압축파일 내에 있는 개별 파일의 정보를 확인하는 함수입니다.

  • filename 파일이름
  • file_size 압축되지 않은 데이터의 크기
  • compress_size 압축된 데이터의 크기
  • date_time 작성날짜
hello = exZip.getinfo('hello.txt')
print(hello.filename)
print(hello.file_size
print(hello.compress_size)
print(hello.date_time)
exZip.close()

#출력값
'''
['hello.txt']
hello.txt
12
12
(2023, 10, 30, 21, 11, 28)
'''