Python,如何创建目录的 zip,同时排除隐藏文件?

问题描述 投票:0回答:1

我有一种情况,我想创建一个目录的 zip,同时在执行此操作时排除所有隐藏文件。

我的用例的具体情况:我有一个目录,其中包含一个小型静态站点构建,但还包含

.git/
和其他非常大的隐藏文件。当我在不忽略隐藏文件的情况下创建 zip 时,当网站本身 <5MB.

时,zip 最终会变得很大(GB)

在忽略这些隐藏文件的同时创建 zip 的有效方法是什么?

python zip
1个回答
0
投票

这看起来效果很好。

import glob
import zipfile

def zip_dir(directory, name) -> str:
    """Compress a directory into a zip. (Ignoring hidden files.)

    Args:
        directory: The directory to make into a .zip
        name: The name of the resulting .zip

    Returns:
        The name of the .zip
    """
    with zipfile.ZipFile(f"{name}.zip", 'w') as f:
        for file in glob(f"{directory}/*"):
            f.write(file)
    return name + ".zip"
© www.soinside.com 2019 - 2024. All rights reserved.