8

使用 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
4

3 回答 3

9

如图所示:Python:在没有目录的情况下将文件放入存档?

解决方案是:

     ''' 
    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()
于 2013-05-29T09:29:32.827 回答
3
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")
于 2020-03-07T10:14:41.513 回答
1

在这种情况下使用可能更好的解决方案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()
于 2018-08-15T11:28:13.783 回答