Following a python tutorial making backups. The code works only if i manually in python make all subfolders for placing final zip file, but that defeats the purpose. 1)I create subfolder backup. 2) But i want to create %Y%m%d folder in it using zip. I pass all the arguments.
# 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
The code above is from book the "byte of python"
Here i use the plain zip command in terminal
(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)
I don't believe there is a way to tell zip
to create the target directory, but this is something you can do yourself using
if not os.path.exists(today):
os.makedirs(today)
Note that makedirs
will recursively create all required directories, meaning that you no longer need os.mkdir(target_dir)
unless you want to keep it.