import os
import time
source = ['D:\\MyDrivers\hotfix'] #這裏能夠用天然字符串表示r',由於windows下的分隔符
與python的有衝突,因此須要轉義字符\
# 2. 備份文件到目標路徑
target_dir = 'F:\\DMDownLoad\\' #這裏的末尾必定不要丟分隔符,否者建立的文件會在F:目錄下,
而不會在DMDownload目錄下
# 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') #time.strftime表示對當前時間的調用,括號內爲參數設定
# 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:
target = today+os.sep+now+'.zip'
#os.sep表示目錄符號,windows下是\\,linux下是/,mac下是:,這裏爲了保證移植性,
因此os.sep會根據系統給出分隔符
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. 用winrar的rar命令壓縮文件,但首先要安裝有winrar且設置winrar到環境變量的路徑path中
zip_command = "rar a %s %s" %(target,''.join(source))
#這行命令以前的全部target 、target_dir、today這些都是字符串,只有在
這個命令和os.makedir中才是真正的表示路徑
# Run the backup
#設置winrar到path環境中,這裏已經手動添加了,若是沒有去掉#號
#os.system('set Path=%Path%;C:\Program Files\WinRAR')
if os.system(zip_command)==0:
print'Successful backup to', target
else:
print'Backup FAILED'python