I am trying to use Python to create a zip-file from a directory. I have looked at How to create a zip archive of a directory in Python? and it works but I have another problem. So I have this:
MyDir
|- DirToZip
| |- SubDir1
| | |- file1.txt
| | |- file2.txt
| |- SubDir2
| | |- file3.txt
| | |- file4.txt
| |- basefile.txt
| |- mimetype
|- create_zip.py
This is my create_zip.py
so far:
import os, zipfile
name = 'DirToZip'
zip_name = name + '.zip'
with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as zip_ref:
for folder_name, subfolders, filenames in os.walk(name):
for filename in filenames:
file_path = os.path.join(folder_name, filename)
zip_ref.write(file_path)
zip_ref.close()
As I said, this works ok as far as the code goes, but the problem is that the zip-file is not created as I want to have it. Now it has the root folder DirToZip
as only folder in the file root and the other files inside that folder. But I would lite to not have that root folder and only have the sub folders in the zip file.
WRONG (what I don't want):
DirToZip.zip
|- DirToZip
| |- SubDir1
| | |- file1.txt
| | |- file2.txt
| |- SubDir2
| | |- file3.txt
| | |- file4.txt
| |- basefile.txt
| |- mimetype
CORRECT (what I want):
DirToZip.zip
|- SubDir1
| |- file1.txt
| |- file2.txt
|- SubDir2
| |- file3.txt
| |- file4.txt
|- basefile.txt
|- mimetype
I tried adding for file in os.listdir(name):
after with zipfile...
and change to ... in os.walk(file)
but that did not work. The zip file became empty instead.
What can I do?