current position:Home>Python standard library zipfile compresses files/folders

Python standard library zipfile compresses files/folders

2022-09-09 01:23:50Likianta我

压缩单个文件

from zipfile import ZipFile
with ZipFile('output.zip', 'w') as z:
    z.write('input.txt')

压缩多个文件

要求:

  • After compressing multiple files, 处于同一目录下 (也就是 zip 文件中, Subdirectory structure is not included)
  • These source files may come from different directories
from os.path import basename
from zipfile import ZipFile

def zip_files(*files):
    with ZipFile('output.zip', 'w') as z:
        for f in files:
            z.write(f, arcname=basename(f))

Compress a single directory

讲解:

When compressing a single directory, ZipFile 需要 write 目录, and every file in the directory (Include files in subfolders) 的路径.

These paths are in zip There is a common prefix in the file, That is, the directory name of the root directory, 如下所示:

output.zip
|= root  # This is the public prefix
   |- aaa.txt
   |- bbb.txt
   |= ccc
      |- ddd.txt
import os
import os.path
from zipfile import ZipFile

def zip_dir(dir_):
    with ZipFile('output.zip', 'w') as z:
        z.write(dir_, arcname=(dn := os.path.basename(dir_)))
        for root, dirs, files in os.walk(dir_):
            for fn in files:
                z.write(
                    fp := os.path.join(root, fn),
                    arcname=dn + '/' + os.path.relpath(fp, dir_)
                    # ^^^^^^^^^^ 特别注意这里.
                )

Compress multiple directories

要求:

  • Take their common path part as a prefix. 例如:

    输入:

    c:
    |= aaa
       |= mmm
          |- foo.txt
       |= nnn
          |- bar.txt
    

    输出:

    result.zip
    |= mmm
       |- foo.txt
    |= nnn
       |- bar.txt
    
import os
import os.path
from zipfile import ZipFile

def zip_dirs(*dirs):
    prefix = os.path.commonprefix(dirs)
    with ZipFile('output.zip', 'w') as z:
        for d in dirs:
            z.write(d, arcname=os.path.relpath(d, prefix))
            for root, dirs, files in os.walk(d):
                for fn in files:
                    z.write(
                        fp := os.path.join(root, fn),
                        arcname=os.path.relpath(fp, prefix)
                    )

脚本

I combined the above snippets into one script, 名称为 “ziputil.py”, 代码如下:

import os
import os.path
from zipfile import ZipFile


def zip_file(file_i: str, file_o: str) -> None:
    with ZipFile(file_o, 'w') as z:
        z.write(file_i, arcname=(n := os.path.basename(file_i)))
        print('zip_file:', n)


def zip_files(*files_i: str, file_o: str) -> None:
    with ZipFile(file_o, 'w') as z:
        for f in files_i:
            z.write(f, arcname=(n := os.path.basename(f)))
            print('zip_files:', n)


def zip_dir(dir_i: str, file_o: str) -> None:
    dir_i_parent = os.path.dirname(dir_i)
    with ZipFile(file_o, 'w') as z:
        z.write(dir_i, arcname=(n := os.path.basename(dir_i)))
        print('zip_dir:', n)
        for root, dirs, files in os.walk(dir_i):
            for fn in files:
                z.write(
                    fp := os.path.join(root, fn),
                    arcname=(n := os.path.relpath(fp, dir_i_parent)),
                )
        print('zip_dir:', n)


def zip_dirs(*dirs_i: str, file_o: str) -> None:
    prefix = os.path.commonprefix(dirs_i)
    with ZipFile(file_o, 'w') as z:
        for d in dirs_i:
            z.write(d, arcname=(n := os.path.relpath(d, prefix)))
            print('zip_dirs:', n)
            for root, dirs, files in os.walk(d):
                for fn in files:
                    z.write(
                        fp := os.path.join(root, fn),
                        arcname=(n := os.path.relpath(fp, prefix)),
                    )
            print('zip_dirs:', n)

实战 (截图)

)

)

copyright notice
author[Likianta我],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/252/202209090109477466.html

Random recommended