Error message if there is a space in the source directory

Peter Otten __peter__ at web.de
Sat Jun 2 18:13:14 EDT 2007


 lukefrancomusic at gmail.com wrote:

> I am trying to learn Python. I am working on a simple backup program
> (code listed below). When using a source directory (the files to be
> backed up) without spaces in the title, my program works fine [see
> line 5]. If I try to access a directory with a space in the name the
> program fails with this error message:
> 
> zip error:Nothing to do! (try: zip -qr C:\Backup\
> \06.02.2007\BackUp at _10.03.57.zip . -i C:\test\test2\\)
> Backup FAILED
> 
> I've been trying to find the answer for a while now but am stumped and
> don't know exactly what to look for. Any help would be greatly
> appreciated!
> 
> 
>    1. # C:\python25\programs\
>    2. # File name: backup3debug.py
>    3. import os, time
>    4. # 1. The files and directories to be backed up are specified in
> a list.
>    5. source = [r'C:\test\test2\\']
>    6. # 2. The backup must be stored in a main backup directory.
>    7. target_directory = r'C:\Backup\\'
>    8. # 3. The files are backed up into a zip file.
>    9. # 4. The name of the directory is the current date.
>   10. today = target_directory + time.strftime('%m.%d.%Y')
>   11. # The current time is the name of the zip archive.
>   12. now = time.strftime('BackUp at _%H.%M.%S')
>   13. # Create the subdirectory if it does not exist already.
>   14. if not os.path.exists(today):
>   15.    os.mkdir(today)
>   16.    print 'Successfully created directory', today
>   17. # The name of the zip file.
>   18. target = os.path.join(today, now + '.zip')
>   19. # 5. We use the standard ''zip'' command to put the files in a
> zip archive.
>   20. zip_command = "zip -qr %s %s" % (target, ' '.join(source))
>   21. print zip_command
>   22. # Run the backup
>   23. if os.system(zip_command) == 0:
>   24.    print 'sucessful backup to', target
>   25. else:
>   26.    print 'Backup FAILED'

I realize that you have good intentions, but this script is commented to
death. Make a guess which points a reader may stumble over and only comment
these.

> When using a source like this on line 5:
> 
> source = [r'C:\test\test 2\\']
> 
> which has a space in the title, the program will not work.

That's because in the line

zip -qr C:\Backup\\06.07.2008\BackUp at _01.02.03.zip C:\test\test 2\\

the shell (or whatever split the above line into separate arguments) has no
way of knowing that "C:\test\test" and "2\\" are intended to be one
argument. Use subprocess.call() instead of os.system(). You can pass it a
list an thus avoid the ambiguity:

zip_command = ["zip", "-qr", target] + source
subprocess.call(zip_command)

Peter




More information about the Python-list mailing list