在 python 中压缩文件时如何保留目录?

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

我有以下功能,我将目录转换为字节,但父目录中的目录没有被保留。如何保留目录?这是我尝试过的:

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()

这是 returns 文件的字节,但是当我打开它时,所有文件都在同一个目录中。我认为在 writestr 中添加 filePath 作为第一个参数就可以了,但事实并非如此。谢谢你的帮助!如果我可以提供任何其他信息,请告诉我。

尝试替换

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

与:

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