#!/usr/bin/python
# Filename: backup_ver4.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['/home/swaroop/byte', '/home/swaroop/bin']
# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that
# 2. The backup must be stored in a main backup directory
target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The current day is the name of the subdirectory in the main directory
today = target_dir + time.strftime('%Y%m%d')
# The current time is the name of the zip archive
now = time.strftime('%H%M%S')
# Take a comment from the user to create the name of the zip file
comment = raw_input('Enter a comment --> ')
if len(comment) == 0: # check if a comment was entered
target = today + os.sep + now + '.zip'
else:
target = today + os.sep + now + '_' + \
comment.replace(' ', '_') + '.zip'
# Notice the backslash!
# Create the subdirectory if it isn't already there
if not os.path.exists(today):
os.mkdir(today) # make directory
print 'Successfully created directory', today
# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'
(源文件:code/backup_ver4.py)
輸出
$ python backup_ver4.py
Enter a comment --> added new examples
Successful backup to /mnt/e/backup/20041208/082156_added_new_examples.zip
$ python backup_ver4.py
Enter a comment -->
Successful backup to /mnt/e/backup/20041208/082316.zip
它如何工作
這個(gè)程序現(xiàn)在工作了!讓我們看一下版本三中作出的實(shí)質(zhì)性改進(jìn)。我們使用 raw_input 函數(shù)得到用戶的注釋,然后通過(guò) len 函數(shù)找出輸入的長(zhǎng)度以檢驗(yàn)用戶是否確實(shí)輸入了什么東西。如果用戶只是按了回車(比如這只是一個(gè)慣例備份,沒(méi)有做什么特別的修改),那么我們就如之前那樣繼續(xù)操作。
然而,如果提供了注釋,那么它會(huì)被附加到 zip 歸檔名,就在.zip 擴(kuò)展名之前。注意我們把注釋中的空格替換成下劃線——這是因?yàn)樘幚磉@樣的文件名要容易得多。