【问题标题】:How do I preserve directories when zipping up a file in python?在 python 中压缩文件时如何保留目录?
【发布时间】:2020-10-14 19:38:08
【问题描述】:

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

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

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

【问题讨论】:

    标签: python-3.x directory zipfile bytesio


    【解决方案1】:

    尝试替换

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

    与:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-28
      • 1970-01-01
      相关资源
      最近更新 更多