zipfile.write():文件的相对路径,在zip存档中重现

时间:2013-05-29 08:47:06

标签: python path zipfile

使用zip文件,我指出位于其他文件夹中的文件,例如:'./data/2003-2007/metropolis/Matrix_0_1_0.csv'

我的问题是,当我提取它时,文件会在./data/2003-2007/metropolis/Matrix_0_1_0.csv中找到,而我希望它在./中提取

这是我的代码:

def zip_files(src, dst):
    zip_ = zipfile.ZipFile(dst, 'w')

    print src, dst

    for src_ in src:
        zip_.write(src_, os.path.relpath(src_, './'), compress_type = zipfile.ZIP_DEFLATED)

    zip_.close()

这是src和dst的打印:

    ['./data/2003-2007/metropolis/Matrix_0_1_0.csv', './data/2003-2007/metropolis/Matrix_0_1_1.csv'] ./data/2003-2007/metropolis/csv.zip

3 个答案:

答案 0 :(得分:4)

如下所示:Python: Getting files into an archive without the directory?

解决方案是:

     ''' 
    zip_file:
        @src: Iterable object containing one or more element
        @dst: filename (path/filename if needed)
        @arcname: Iterable object containing the names we want to give to the elements in the archive (has to correspond to src) 
'''
def zip_files(src, dst, arcname=None):
    zip_ = zipfile.ZipFile(dst, 'w')

    print src, dst
    for i in range(len(src)):
        if arcname is None:
            zip_.write(src[i], os.path.basename(src[i]), compress_type = zipfile.ZIP_DEFLATED)
        else:
            zip_.write(src[i], arcname[i], compress_type = zipfile.ZIP_DEFLATED)

    zip_.close()

答案 1 :(得分:2)

import os
import zipfile

def zipdir(src, dst, zip_name):
    """
    Function creates zip archive from src in dst location. The name of archive is zip_name.
    :param src: Path to directory to be archived.
    :param dst: Path where archived dir will be stored.
    :param zip_name: The name of the archive.
    :return: None
    """
    ### destination directory
    os.chdir(dst)
    ### zipfile handler
    ziph = zipfile.ZipFile(zip_name, 'w')
    ### writing content of src directory to the archive
    for root, dirs, files in os.walk(src):
        for file in files:
            ### In this case the structure of zip archive will be:
            ###       C:\Users\BO\Desktop\20200307.zip\Audacity\<content of Audacity dir>
            # ziph.write(os.path.join(root, file), arcname=os.path.join(root.replace(os.path.split(src)[0], ""), file))

            ### In this case the structure of zip archive will be:
            ###       C:\Users\BO\Desktop\20200307.zip\<content of Audacity dir>
            ziph.write(os.path.join(root, file), arcname=os.path.join(root.replace(src, ""), file))
    ziph.close()


if __name__ == '__main__':
    zipdir("C:/Users/BO/Documents/Audacity", "C:/Users/BO/Desktop", "20200307.zip")

答案 2 :(得分:0)

在这种情况下,使用tarfile可能是更好的解决方案:

with tarfile.open(output, "w:gz") as tar:
    # if we do not provide arcname, archive will include full paths
    arcname = path.split('/')[-1]
    tar.add(path, arcname)
    tar.close()