ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • tar / zip
    python/기본 2022. 5. 2. 13:39
    import tarfile
    
    # tar.gz 파일 생성하기
    with tarfile.open('test.tar.gz', 'w:gz') as tr:
        tr.add('test_dir')
    
    # tar.gz 파일 압축풀기
    with tarfile.open('test.tar.gz', 'r:gz') as tr:
        tr.extractall(path='test_tar')
    
        # 특정 파일의 내용만 볼 때
        with tr.extractfile('test_dir/sub_dir/sub_test.txt') as f:
            print(f.read())
    
    ####################################################################
    import zipfile
    
    with zipfile.ZipFile('test.zip', 'w') as z:
        z.write('test_dir')  # test_dir 생성
        z.write('test_dir/test.txt')  # 이렇게 모두 하나씩 지정 해야함
    
    # 위의 지정 방식이 불편하니..
    import glob
    
    with zipfile.ZipFile('test.zip', 'w') as z:
        for f in glob.glob('test_dir/**', recursive=True):
            print(f)
            z.write(f)
    
    # zip 압축 풀기
    with zipfile.ZipFile('test.zip', 'r') as z:
        z.extractall(path='test_zip')  # test_zip dir 에 압축 품
    
        # 특정 파일만 볼 때
        with z.open('test_dir/test.txt') as f:
            print(f.read())

     

    https://docs.python.org/ko/3/library/shutil.html 를 이용해서 간단한 경우 압축을 쉽게 할 수 있다.

    shutil.make_archive('/tmp/dir', format='zip', root_dir='/tmp/dir')

    'python > 기본' 카테고리의 다른 글

    datetime / time  (0) 2022.05.02
    tempfile / subprocess  (0) 2022.05.02
    os, pathlib, glob, shutil  (0) 2022.05.01
    Template, Csv  (0) 2022.05.01
    File  (0) 2022.05.01

    댓글

Designed by Tistory.