创建zip文件时出现嵌套目录

时间:2016-09-10 08:59:58

标签: python zipfile

我是python的新手。我正在尝试创建“diveintomark-diveintopython3-793871b”目录的zip文件。我使用os.chdir()函数更改了当前的工作目录。创建了zip文件但是问题当我提取zip文件时,我得到以下目录

Users/laiba/Desktop/diveintomark-diveintopython3-793871b 

但我只想在我的zip文件夹中找到 diveintomark-diveintopython3-793871b 文件夹而不是整个嵌套目录。为什么会发生这种情况以及如何解决这个问题?

import zipfile, os

os.chdir('c:\\Users\\laiba\\Desktop')
myzip=zipfile.ZipFile('diveZip.zip','w',zipfile.ZIP_DEFLATED)

for folder,subfolder,file in os.walk('diveintomark-diveintopython3-793871b'):
    myzip.write(folder)
    for each in subfolder:
        myzip.write(os.path.abspath(os.path.join(folder,each)))
    for each in file:
        myzip.write(os.path.abspath(os.path.join(folder,each)))

1 个答案:

答案 0 :(得分:2)

您可以使用参数arcname:归档中项目的名称而不是完整路径名称。但是在这里你不需要它,因为你已经在正确的目录中。只需删除abspath即可完成(以及重复的文件夹条目)

import zipfile, os

os.chdir('c:\\Users\\laiba\\Desktop')

myzip=zipfile.ZipFile('diveZip.zip','w',zipfile.ZIP_DEFLATED)

for folder,subfolder,file in os.walk('diveintomark-diveintopython3-793871b'):
    for each in subfolder+file:
        myzip.write(os.path.join(folder,each))
myzip.close()

这可以不改变目录,但更复杂,更优雅,因为你没有chdir

import zipfile, os

root_dir = r"c:\Users\laiba\Desktop"
myzip=zipfile.ZipFile(os.path.join(root_dir,'diveZip.zip'),'w',zipfile.ZIP_DEFLATED)

for folder,subfolder,file in os.walk(os.path.join(root_dir,'diveintomark-diveintopython3-793871b')):
    for each in subfolder+file:
        source = os.path.join(folder,each)
        # remove the absolute path to compose arcname
        # also handles the remaining leading path separator with lstrip
        arcname = source[len(root_dir):].lstrip(os.sep)
        # write the file under a different name in the archive
        myzip.write(source,arcname=arcname)

myzip.close()