'Zip Multiple folder - Python
I am working on zip the multiple folder in python When i ran the code it's creating name1.zip and name2.zip and open the name1.zip file it only showing the file1.pdf.
What i am trying is when i open name1.zip file it will come with parent folder name1
Folder structure
test --> name1 --> file1.pdf
Could someone help me out Thanks This is my code:
import os
import zipfile
path = "/Users/Documents/test"
path = os.path.abspath(os.path.normpath(os.path.expanduser(path)))
for folder in os.listdir(path):
zipf = zipfile.ZipFile('{0}.zip'.format(os.path.join(path, folder)), 'w', zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(os.path.join(path, folder)):
for filename in files:
zipf.write(os.path.abspath(os.path.join(root, filename)), arcname=filename)
zipf.close()
Solution 1:[1]
That's what the arcname parameter is for. Try
zipf.write(
os.path.abspath(os.path.join(root, filename)),
arcname=os.path.relpath(os.path.join(root, filename), start=path)
)
instead of
zipf.write(os.path.abspath(os.path.join(root, filename)), arcname=filename)
Also, have a look at pathlib. Makes for more readable code IMHO.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
