为什么 Python zipfile 模块在 zip 文件中创建完整路径

Why Python zipfile module creates full path inside the zip file

我需要将给定目录(test1 内)中的所有文件压缩到一个 zip 文件中。

我的密码是

import zipfile
zipf = zipfile.ZipFile('/media/test/test1/'+'my_zip.zip', 'w', zipfile.ZIP_DEFLATED)
#Here I mentioned the path for specifying where the zip file should created
path='/media/test/test1/'
for root, dirs, files in os.walk(path):
    for file in files:
        if not str(file).endswith('.zip'):
            zipf.write(os.path.join(root, file))
zipf.close()

这给出了 my_zip.zip

的输出

当我打开它时,它包含每个子文件夹,例如 media>test>test1>test 1

中的文件

但我不想要这个 media>test>test1。如何实现?

如果您没有传递应在存档中使用的名称,则 zipfile 使用传递到 write()

中的路径

试试这个:

 zipf.write(os.path.join(root, file), 
            arcname=os.path.join(root.replace(path, '', 1), file))