6

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?

1
  • 1
    zip_ref.write(filename) - method has additional parameter arcname, you can just change it from defaulting to filename as you like Commented Nov 20, 2019 at 13:26

1 Answer 1

5

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Isn't it wrapped under with specifically so you don't have to explicitly close the zip_ref after?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.