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 に答える