Warm tip: This article is reproduced from serverfault.com, please click

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

发布于 2020-10-14 19:38:08

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.

Questioner
Jake West
Viewed
0
GordonAitchJay 2020-11-30 13:11:07

Try replacing

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

with:

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