简体   繁体   中英

Why Python zipfile module creates full path inside the zip file

I need to zip all files in a given directory(inside test1) into a zip file.

My code is

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()

This gives the output of my_zip.zip

When I open this, it contains each subfolder like media>test>test1>files in test 1

But I don't want this media>test>test1. How to achieve that?

Thanks in advance.

If you do not pass the name that should be used in the archive, then zipfile uses the path that was passed into write()

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM