As the design of our program is now reasonably stable, we can write the code which is an implementation of our solution.
Save as backup_ver1.py:
import os import time
# 1. The files and directories to be backed up are
# specified in a list.
# Example on Windows:
# source = ['"C:\\My Documents"', 'C:\\Code']
# Example on Mac OS X and Linux:
source = ['/Users/swa/notes']
# Notice we had to use double quotes inside the string
# for names with spaces in it.
# 2. The backup must be stored in a
# Remember to change this to which folder you will be using
# 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time target = target_dir + os.sep + \
time.strftime('%Y%m%d%H%M%S') + '.zip'
# Create target directory if it is not present if not os.path.exists(target_dir):
os.mkdir(target_dir) # make directory
# 5. We use the zip command to put the files in a zip archive zip_command = "zip -r {0} {1}".format(target,
' '.join(source))
Problem Solving
print 'Successful backup to', target else:
adding: Users/swa/notes/ (stored 0%)
adding: Users/swa/notes/blah1.txt (stored 0%) adding: Users/swa/notes/blah2.txt (stored 0%) adding: Users/swa/notes/blah3.txt (stored 0%)
Successful backup to /Users/swa/backup/20140328084844.zip
Now, we are in the testing phase where we test that our program works properly. If it doesn’t behave as expected, then we have to debug our program i.e. remove the bugs (errors) from the program.
If the above program does not work for you, copy the line printed after the Zip command is line in the output, paste it in the shell (on GNU/Linux and Mac OS X) / cmd (on Windows), see what the error is and try to fix it. Also check the zip command manual on what could be wrong. If this command succeeds, then the problem might be in the Python program itself, so check if it exactly matches the program written above.
How It WorksYou will notice how we have converted our design into code in a step-by-step manner.
We make use of the os and time modules by first importing them. Then, we specify the files and directories to be backed up in the source list. The target directory is where we store all the backup files and this is specified in the target_dir variable.
The name of the zip archive that we are going to create is the current date and time which we generate using the time.strftime() function. It will also have the .zip extension and will be stored in the target_dir directory.
Notice the use of the os.sep variable - this gives the directory separator according to your operating system i.e. it will be '/' in GNU/Linux and Unix, it will be '\\' in Windows and ':' in Mac OS. Using os.sep instead of these characters directly will make our program portable and work across all of these systems.
The time.strftime() function takes a specification such as the one we have used in the above program. The %Y specification will be replaced by the year with the
Problem Solving
century. The %m specification will be replaced by the month as a decimal number between 01 and 12 and so on. The complete list of such specifications can be found in the Python Reference Manual3.
We create the name of the target zip file using the addition operator which concatenates the strings i.e. it joins the two strings together and returns a new one. Then, we create a string zip_command which contains the command that we are going to execute.
You can check if this command works by running it in the shell (GNU/Linux terminal or DOS prompt).
The zip command that we are using has some options and parameters passed. The -r option specifies that the zip command should work recursively for directories i.e.
it should include all the subdirectories and files. The two options are combined and specified in a shortcut as -qr. The options are followed by the name of the zip archive to create followed by the list of files and directories to backup. We convert the source list into a string using the join method of strings which we have already seen how to use.
Then, we finally run the command using the os.system function which runs the command as if it was run from the system i.e. in the shell - it returns 0 if the command was successfully, else it returns an error number.
Depending on the outcome of the command, we print the appropriate message that the backup has failed or succeeded.
That’s it, we have created a script to take a backup of our important files!
Note to Windows Users
Instead of double backslash escape sequences, you can also use raw strings. For example, use 'C:\\Documents' or r’C:
\Documents'. However, do not use 'C:\Documents' since you end up using an unknown escape sequence \D.
Now that we have a working backup script, we can use it whenever we want to take a backup of the files. This is called the operation phase or the deployment phase of the software.
The above program works properly, but (usually) first programs do not work exactly as you expect. For example, there might be problems if you have not designed the program
3 http://docs.python.org/2/library/time.html#time.strftime
Problem Solving
properly or if you have made a mistake when typing the code, etc. Appropriately, you will have to go back to the design phase or you will have to debug your program.