【问题标题】:zip command in Mac refuses to create folderMac中的zip命令拒绝创建文件夹
【发布时间】:2021-11-15 18:46:56
【问题描述】:

按照 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的字节》一书

这里我在终端中使用普通的 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)

【问题讨论】:

    标签: python zip backup


    【解决方案1】:

    我不相信有办法告诉zip 创建目标目录,但这是您可以自己使用的方法

    if not os.path.exists(today):
        os.makedirs(today)
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-01
      • 1970-01-01
      • 2020-08-11
      • 2013-07-10
      相关资源
      最近更新 更多