我具有以下函数,其中将目录转换为字节,但未保留父目录内的目录。如何保存目录?这是我尝试过的:
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.join(folderName, filename)
和:
filePath = os.path.relpath(os.path.join(folderName, filename), path_to_extension_directory)