How do I preserve directories when zipping up a file in python?

122 views Asked by At

I have the following function where I convert a directory to bytes, but the directories inside the parent directory are not being preserved. How do I preserve the directories? Here's what I have tried:

buf = io.BytesIO()
    zipObj = ZipFile(buf, "w")
    with zipObj:
        # Iterate over all the files in directory
        for folderName, subfolders, filenames in os.walk(path_to_extension_directory):
            for filename in filenames:
                # create complete filepath of file in directory
                filePath = os.path.join(folderName, filename)
                with open(f"{folderName}/{filename}", 'rb') as file_data:
                    bytes_content = file_data.read()
                # Add file to zip
                zipObj.writestr(filePath, bytes_content)
    # Rewind the buffer's file pointer (may not be necessary)
    buf.seek(0)
    return buf.read()

This returns the bytes of the files but when I open it, all of the files are in the same directory. I thought that adding the filePath as the first parameter in writestr would do it, but it does not. Thanks for your help! Please let me know if I can provide any additional information.

1

There are 1 answers

0
GordonAitchJay On BEST ANSWER

Try replacing

filePath = os.path.join(folderName, filename)

with:

filePath = os.path.relpath(os.path.join(folderName, filename), path_to_extension_directory)