[英]ZipFile inside a ZipFile (Python)
BACKGROUND背景
I have some directory in my home directory called delivery_content
.我的主目录中有一些名为
delivery_content
目录。 Inside that directory there are two folders content_123
and content_456
.在该目录中有两个文件夹
content_123
和content_456
。 Each directory contains a text file.每个目录包含一个文本文件。 So the over all structure looks like the following.
所以整体结构如下所示。
-delivery_content
-content_123/
-content_123.txt
-content_456/
-content_456.txt
I am writing code that when given a directory it will zip all of it's contents.我正在编写代码,当给定一个目录时,它将压缩所有内容。
CODE代码
import os
import shutil
from pathlib import Path
from datetime import datetime
DOWNLOAD_DIR = Path(os.getenv("HOME")) / "delivery_content"
date = datetime.today().strftime("%Y-%m-%d")
delivery_name = f"foo_{date}"
shutil.make_archive(str(DOWNLOAD_DIR / delivery_name), "zip", str(DOWNLOAD_DIR))
print("Zipping Has Complete")
So for the given code above i expect to see a foo_todays_date.zip in the DOWNLOAD_DIR
and when i unzip it i expect to see the following因此,对于上面给定的代码,我希望在
DOWNLOAD_DIR
看到 foo_todays_date.zip,当我解压缩它时,我希望看到以下内容
-content_123/
-content_123.txt
-content_456/
-content_456.txt
However I see the following但是我看到以下内容
Is there a way i can avoid having a .zip inside my zipfile?有没有办法避免在我的 zipfile 中包含 .zip?
The problem is that you are putting the zip file inside the directory that you are archiving.问题是您将 zip 文件放在要归档的目录中。
make_archive
is probably creating an empty file to verify it can write to the destination before it starts archiving. make_archive
可能正在创建一个空文件以验证它可以在开始归档之前写入目标。 So it then sees the empty zip file as a file to archive.因此,它将空的 zip 文件视为要存档的文件。 The only way I see around this using the
make_archive
function is to put the archive file outside of the directory to archive like below:我使用
make_archive
函数看到的唯一方法是将存档文件放在目录之外进行存档,如下所示:
shutil.make_archive(str(DOWNLOAD_DIR / ".."/ delivery_name), "zip", str(DOWNLOAD_DIR))
You can always move the zip file into the DOWNLOAD_DIR afterward.之后您始终可以将 zip 文件移动到 DOWNLOAD_DIR 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.