I asked this question on StackOverflow and they just linked me to other questions that I already read and tried.

I have been trying to create a zip file using zipfile in Python, but it keeps zipping all folders that are included in the absolute path. I just want to zip the file that the path leads to, not all of the files in that path.

If I try to create a zip file named "Zip_Files.zip" from this path:


When I try to zip this I end up with a zip folder like this:

Zip_Files -> Users -> UserName -> Documents -> Folder_to_be_zipped -> {contents of Folder_to_be_zipped}

I want something like this:

Zip_Files.zip -> Folder_to_be_zipped -> {contents of Folder_to_be_zipped}

I only want to zip Folder_to_be_zipped, not every file leading to that folder.

This code gives me the Zip_Files.zip -> Folder_to_be_zipped but there's nothing inside of Folder_to_be_zipped and I know that's because zipfile isn't recursive.

from os.path import basename
zip.write(first_path, basename(first_path))
zip.write(second_path, basename(second_path))

This code gives me Zip_Files.zip -> Users -> UserName -> Documents -> Folder_to_be_zipped -> {contents of Folder_to_be_zipped}

import os
import zipfile

def zipdir(path, zip):
    for root, dirs, files in os.walk(path):
        for file in files:
            zip.write(os.path.join(root, file))

if __name__ == '__main__':
    zipf = zipfile.ZipFile('Python.zip', 'w')
    zipdir('C:/Users/UserName/Documents/Folder_to_be_zipped/', zipf)

So I know that my solution is somewhere in the middle of these two pieces of code, but I am relatively new to Python and I can't figure it out. Hopefully you guys can give me the code to make this work.

Edited by A-M-G

4 Years
Discussion Span
Last Post by Gribouillis

Did you try

    oldwd = os.getcwd()
        zipdir('Folder_to_be_zipped', zipf)


Edited by Gribouillis

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.