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