如何使用 python(版本 2.5)压缩文件夹的内容?

发布于 2024-07-09 04:52:16 字数 88 浏览 6 评论 0原文

一旦我在特定文件夹中拥有了所需的所有文件,我希望我的 python 脚本能够压缩文件夹内容。

这可能吗?

我该如何去做呢?

Once I have all the files I require in a particular folder, I would like my python script to zip the folder contents.

Is this possible?

And how could I go about doing it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

清欢 2024-07-16 04:52:16

在 python 2.7 上,您可以使用: shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run [,所有者[,组[,记录器]]]]]]])

base_name 存档名称减去

的扩展名format 格式

要压缩的存档root_dir 目录

。 例如

 shutil.make_archive(target_file, format="bztar", root_dir=compress_me)    

On python 2.7 you might use: shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]]).

base_name archive name minus extension

format format of the archive

root_dir directory to compress.

For example

 shutil.make_archive(target_file, format="bztar", root_dir=compress_me)    
初雪 2024-07-16 04:52:16

脚本的改编版本是:

#!/usr/bin/env python
from __future__ import with_statement
from contextlib import closing
from zipfile import ZipFile, ZIP_DEFLATED
import os

def zipdir(basedir, archivename):
    assert os.path.isdir(basedir)
    with closing(ZipFile(archivename, "w", ZIP_DEFLATED)) as z:
        for root, dirs, files in os.walk(basedir):
            #NOTE: ignore empty directories
            for fn in files:
                absfn = os.path.join(root, fn)
                zfn = absfn[len(basedir)+len(os.sep):] #XXX: relative path
                z.write(absfn, zfn)

if __name__ == '__main__':
    import sys
    basedir = sys.argv[1]
    archivename = sys.argv[2]
    zipdir(basedir, archivename)

示例:

C:\zipdir> python -mzipdir c:\tmp\test test.zip

它创建'C:\zipdir\test.zip' 存档,其中包含 'c:\tmp\test' 目录的内容。

Adapted version of the script is:

#!/usr/bin/env python
from __future__ import with_statement
from contextlib import closing
from zipfile import ZipFile, ZIP_DEFLATED
import os

def zipdir(basedir, archivename):
    assert os.path.isdir(basedir)
    with closing(ZipFile(archivename, "w", ZIP_DEFLATED)) as z:
        for root, dirs, files in os.walk(basedir):
            #NOTE: ignore empty directories
            for fn in files:
                absfn = os.path.join(root, fn)
                zfn = absfn[len(basedir)+len(os.sep):] #XXX: relative path
                z.write(absfn, zfn)

if __name__ == '__main__':
    import sys
    basedir = sys.argv[1]
    archivename = sys.argv[2]
    zipdir(basedir, archivename)

Example:

C:\zipdir> python -mzipdir c:\tmp\test test.zip

It creates 'C:\zipdir\test.zip' archive with the contents of the 'c:\tmp\test' directory.

烟花易冷人易散 2024-07-16 04:52:16

这是一个递归版本

def zipfolder(path, relname, archive):
    paths = os.listdir(path)
    for p in paths:
        p1 = os.path.join(path, p) 
        p2 = os.path.join(relname, p)
        if os.path.isdir(p1): 
            zipfolder(p1, p2, archive)
        else:
            archive.write(p1, p2) 

def create_zip(path, relname, archname):
    archive = zipfile.ZipFile(archname, "w", zipfile.ZIP_DEFLATED)
    if os.path.isdir(path):
        zipfolder(path, relname, archive)
    else:
        archive.write(path, relname)
    archive.close()

Here is a recursive version

def zipfolder(path, relname, archive):
    paths = os.listdir(path)
    for p in paths:
        p1 = os.path.join(path, p) 
        p2 = os.path.join(relname, p)
        if os.path.isdir(p1): 
            zipfolder(p1, p2, archive)
        else:
            archive.write(p1, p2) 

def create_zip(path, relname, archname):
    archive = zipfile.ZipFile(archname, "w", zipfile.ZIP_DEFLATED)
    if os.path.isdir(path):
        zipfolder(path, relname, archive)
    else:
        archive.write(path, relname)
    archive.close()
懒的傷心 2024-07-16 04:52:16

jfs 的解决方案和 Kozyarchuk 的解决方案都适用于 OP 的用例,但是:

  • jfs 的解决方案将源文件夹中的所有文件进行压缩,并将它们存储在根级别的 zip 中(不保留 zip 结构中的原始源文件夹) )。
  • Kozyarchuk 的解决方案无意中将新创建的 zip 文件放入其自身中,因为它是一个递归解决方案(例如,使用此代码创建新的 zip 文件“myzip.zip”将导致存档“myzip.zip”本身包含一个空文件“myzip.zip”)。因此

,这里有一个解决方案,只需将源文件夹(以及任何深度的任何子文件夹)添加到 zip 存档中。 这是因为您无法将文件夹名称传递给内置方法 ZipFile.write() - 下面的函数 add_folder_to_zip() 提供了将文件夹及其所有内容添加到 zip 存档的简单方法。 下面的代码适用于 Python2 和 Python3。

import zipfile
import os

def add_folder_to_zip(src_folder_name, dst_zip_archive):
    """ Adds a folder and its contents to a zip archive

        Args:
            src_folder_name (str): Source folder name to add to the archive
            dst_zip_archive (ZipFile):  Destination zip archive

        Returns:
            None
    """
    for walk_item in os.walk(src_folder_name):
        for file_item in walk_item[2]:
            # walk_item[2] is a list of files in the folder entry
            # walk_item[0] is the folder entry full path 
            fn_to_add = os.path.join(walk_item[0], file_item)
            dst_zip_archive.write(fn_to_add)

if __name__ == '__main__':
    zf = zipfile.ZipFile('myzip.zip', mode='w')
    add_folder_to_zip('zip_this_folder', zf)
    zf.close()

Both jfs's solution and Kozyarchuk's solution could work for the OP's use case, however:

  • jfs's solution zips all of the files in a source folder and stores them in the zip at the root level (not preserving the original source folder within the structure of the zip).
  • Kozyarchuk's solution inadvertently puts the newly-created zip file into itself since it is a recursive solution (e.g. creating new zip file "myzip.zip" with this code will result in the archive "myzip.zip" itself containing an empty file "myzip.zip")

Thus, here is a solution that will simply add a source folder (and any subfolders to any depth) to a zip archive. This is motivated by the fact that you cannot pass a folder name to the built-in method ZipFile.write() -- the function below, add_folder_to_zip(), offers a simple method to add a folder and all of its contents to a zip archive. Below code works for Python2 and Python3.

import zipfile
import os

def add_folder_to_zip(src_folder_name, dst_zip_archive):
    """ Adds a folder and its contents to a zip archive

        Args:
            src_folder_name (str): Source folder name to add to the archive
            dst_zip_archive (ZipFile):  Destination zip archive

        Returns:
            None
    """
    for walk_item in os.walk(src_folder_name):
        for file_item in walk_item[2]:
            # walk_item[2] is a list of files in the folder entry
            # walk_item[0] is the folder entry full path 
            fn_to_add = os.path.join(walk_item[0], file_item)
            dst_zip_archive.write(fn_to_add)

if __name__ == '__main__':
    zf = zipfile.ZipFile('myzip.zip', mode='w')
    add_folder_to_zip('zip_this_folder', zf)
    zf.close()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文