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

这将返回文件的字节,但是当我打开它时,所有文件都在同一目录中。我以为将filePath添加为writestr中的第一个参数可以做到,但事实并非如此。谢谢你的帮助!请让我知道是否可以提供其他信息。

解决方法

尝试更换

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

具有:

{{1}}