在 Python 中创建 .zip? [英] Create .zip in Python?

查看:29
本文介绍了在 Python 中创建 .zip?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的脚本中创建一个函数,用于将给定源目录 (src) 的内容压缩到一个 zip 文件 (dst).例如zip('/path/to/dir', '/path/to/file.zip'),其中/path/to/dir是一个目录,并且 /path/to/file.zip 尚不存在.我不想压缩目录本身,这对我来说完全不同.我想压缩目录中的文件(和子目录).这就是我正在尝试的:

I'm trying to create a function in my script that zips the contents of a given source directory (src) to a zip file (dst). For example, zip('/path/to/dir', '/path/to/file.zip'), where /path/to/dir is a directory, and /path/to/file.zip doesn't exist yet. I do not want to zip the directory itself, this makes all the difference in my case. I want to zip the files (and subdirs) in the directory. This is what I'm trying:

def zip(src, dst):
    zf = zipfile.ZipFile("%s.zip" % (dst), "w")
    for dirname, subdirs, files in os.walk(src):
        zf.write(dirname)
        for filename in files:
            zf.write(os.path.join(dirname, filename))
    zf.close()

这将创建一个本质上是 / 的 zip.例如,如果我压缩 /path/to/dir,解压缩 zip 会创建一个目录,其中包含path",该目录中包含to"等.

This creates a zip that is essentially /. For example, if I zipped /path/to/dir, extracting the zip creates a directory with "path" in it, with "to" in that directory, etc.

有没有人有一个不会导致这个问题的函数?

Does anyone have a function that doesn't cause this problem?

我再怎么强调也不为过,它需要压缩目录中的文件,而不是目录本身.

I can't stress this enough, it needs to zip the files in the directory, not the directoy itself.

推荐答案

zipfile.write() 方法接受一个可选的 arcname 参数指定 zipfile 中文件的名称.

The zipfile.write() method takes an optional arcname argument that specifies what the name of the file should be inside the zipfile.

您可以使用它去除开头的 src 路径.我在这使用 os.path.abspath() 确保 srcos.walk() 返回的文件名有一个共同的前缀.

You can use this to strip off the path to src at the beginning. Here I use os.path.abspath() to make sure that both src and the filename returned by os.walk() have a common prefix.

#!/usr/bin/env python2.7

import os
import zipfile

def zip(src, dst):
    zf = zipfile.ZipFile("%s.zip" % (dst), "w", zipfile.ZIP_DEFLATED)
    abs_src = os.path.abspath(src)
    for dirname, subdirs, files in os.walk(src):
        for filename in files:
            absname = os.path.abspath(os.path.join(dirname, filename))
            arcname = absname[len(abs_src) + 1:]
            print 'zipping %s as %s' % (os.path.join(dirname, filename),
                                        arcname)
            zf.write(absname, arcname)
    zf.close()

zip("src", "dst")

目录结构如下:

src
└── a
    ├── b
    │   └── bar
    └── foo

脚本打印:

zipping src/a/foo as a/foo
zipping src/a/b/bar as a/b/bar

生成的 zip 文件的内容是:

And the contents of the resulting zip file are:

Archive:  dst.zip
  Length     Date   Time    Name
 --------    ----   ----    ----
        0  01-28-13 11:36   a/foo
        0  01-28-13 11:36   a/b/bar
 --------                   -------
        0                   2 files

这篇关于在 Python 中创建 .zip?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆