As another answerer has noted, the code you're using is Windows-specific and the amendments that the other answer suggested will be required to make it work in OSX.
To diagnose the problem I've made some amendments to your code as follows (changing some commas to apostrophes, changing the strftime()
call and adding a print()
to show what is actually in zip_command
):
import os
import time
source = ['C:\\learningPython','C:\\scan']
target_dir = 'C:/backup'
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip' # modified
zip_command = "zip -qr {0} {1}".format(target, ' '.join(source))
print(zip_command) # added - see discussion below
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')
When I also created the three folders c:\backup
, c:\learningPython
and c:\scan
and put a file in c:\learningPython
so that zip
had something to do, the amended script gave the following output on my Windows PC:
C:\usr\sjl\dev\test\python>python ziptest.py
zip -qr C:/backup\20130116152602.zip C:\learningPython C:\scan
Successful backup to C:/backup\20130116152602.zip
... which is, I think, what you were hoping for.
I find that when I'm running system commands from Python it always pays to print the command out, exactly as I'm asking os.system()
to run it, so that I know exactly what is going to be run (and so I can try that command from the shell manually if it doesn't do what I think it should do).
I've also modified the format string in strftime()
because the original version had a capital 'M' after the 'Y' (which would have shown the number of minutes rather than the number of months) and a capital 'D' instead of a 'd' for the day number. 'D' isn't a valid code letter in a strftime()
format string (see here). For me, using Python 3.2, the wrong letter caused a runtime error when I tried to run the script.
With respect to your other question, source
is a list of the directories that zip
is being asked to process. If you only need to process one directory, you could as easily write the line starting with zip_command
as (with the folder name in OS X / Unix style this time):
zip_command = "zip -qr {0} {1}".format(target, '/Users/yourusername/Documents'))