Mac 中的 zip 命令拒绝创建文件夹

zip command in Mac refuses to create folder

按照 python 教程进行备份。仅当我在 python 中手动创建用于放置最终 zip 文件的所有子文件夹时,该代码才有效,但这违背了目的。 1)我创建子文件夹备份。 2) 但我想使用 zip 在其中创建 %Y%m%d 文件夹。我通过了所有参数。

# pylint: disable=missing-module-docstring
import os
import time
source = "/Users/bogdan/Downloads/tests/new/"

target_dir = os.path.join(source, "backup")

today = target_dir+os.sep+time.strftime("%Y%m%d")
now = time.strftime("%H%M%S")


if not os.path.exists(target_dir): #create a subdirectory for backups
    os.mkdir(target_dir)
    print("Created backup dir")

target = today+os.sep+now+".zip" #HERE IS THE PROBLEM. the Zip command will work only if folder  "today"(variables filled) already  exists in parent backup folder. But i want zip command to CREATE it(it contains Year,date etc.. 

zip_command = r"zip -qr {0} {1}".format(target, source)

print(zip_command)
zip_command

以上代码来自书本python

的“byte”

这里我在终端中使用普通的 zip 命令

(base) bogdan@MacBook-Air-Bogdan main % zip -qr /Users/bogdan/Downloads/tests/new/backup/20210922/123228.zip /Users/bogdan/Downloads/tests/new
zip I/O error: No such file or directory
zip error: Could not create output file (/Users/bogdan/Downloads/tests/new/backup/20210922/123228.zip)

我认为没有办法告诉 zip 创建目标目录,但您可以使用

自行完成此操作
if not os.path.exists(today):
    os.makedirs(today)

请注意 makedirs 将递归创建所有必需的目录,这意味着您不再需要 os.mkdir(target_dir) 除非您想保留它。