Skip to content

Instantly share code, notes, and snippets.

@makerj
Last active February 9, 2016 06:26
Show Gist options
  • Save makerj/23e695d23bd3e8aab5bc to your computer and use it in GitHub Desktop.
Save makerj/23e695d23bd3e8aab5bc to your computer and use it in GitHub Desktop.
#Python zip archive of a directory

#Python zip archive of a directory

디렉토리를 .zip 파일로 압축하는 것은 자주 있는 일이다. 짧은 코드로 글을 정리한다. 참조

##무압축


방법은 zipfile, shutil 모듈을 사용한 방법으로 나뉜다. 결과는 같으나 편리함이 다르다.

###shutil

import shutil
shutil.make_archive(output_filename, 'zip', dir_name)

###zipfile

import os
import zipfile

def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file))

if __name__ == '__main__':
    zipf = zipfile.ZipFile('Python.zip', 'w')
    zipdir('tmp/', zipf)
    zipf.close()

shutil을 사용한 경우보다 코드가 약간 길지만, 이 방법을 사용하면 for file in files: 부분에서 원하는 파일만 선택 하는 등의 추가 동작이 가능하다.

##압축


import os
import zipfile

def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file))

if __name__ == '__main__':
    zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)
    zipdir('tmp/', zipf)
    zipf.close()

zipfile.ZIP_DEFLATED 옵션을 넣어주면 된다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment