3

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?

BluePrint
  • 1,926
  • 4
  • 28
  • 49
  • 1
    ```zip_ref.write(filename)``` - method has additional parameter arcname, you can just change it from defaulting to filename as you like – Sav Nov 20 '19 at 13:26

1 Answers1

2

It's simple as that:

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, arcname=os.path.relpath(file_path, name))

zip_ref.close()
Sav
  • 616
  • 3
  • 9