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

directory-在python中压缩文件时,如何保存目录?

(directory - How do I preserve directories when zipping up a file in 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()

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

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

尝试更换

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

和:

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