參考一《簡明python教程》:http://old.sebug.net/paper/python/index.html
1,《簡明python教程》第10章的文件備份示例四中,需要用到zip命令,而windows下是沒有,下載了7z-zip代替,同時將7z路徑添加到環境變量中。因此文件拷貝命令需要根據7z.exe命令行參數作相應修改;
#1. the file and directories to be backed up are specified in a list.
#source = r'C:\Users\YU\Documents\NotePad++'
source = r'C:\Users\YU\Documents\NotePad++\*'
#2.The backup must be stored in a main backup directory
target_dir = 'G:\\Yu\\NppBackup\\'
#5.We use the zip command to put the files in a zip archive
zip_command = "7z a -tzip %s %s" % (target,source)
2,windows下python表示文件路徑的兩種方式
在上面代碼中有兩種表述文件路徑的方式:a.用自然字符串表示,在字符串前加‘r',不使用轉義字符,如source文件路徑;b.使用轉義字符,如target_dir文件路徑
3,python使用mkdir函數出現錯誤 WindowsError:[Error 3]
參考二:python使用mkdir函數出現錯誤WindowsError:[Error 3]的解決辦法
原因是’mkdir‘只能創建單層文件夾,如果創建嵌套文件夾則需要使用’makedirs‘
4,完整代碼
#!/usr/bin/python
# _*_ coding: utf-8 _*_
import os
import time
#1. the file and directories to be backed up are specified in a list.
#source = r'C:\Users\YU\Documents\NotePad++'
source = r'C:\Users\YU\Documents\NotePad++\*'
#2.The backup must be stored in a main backup directory
target_dir = 'G:\\Yu\\NppBackup\\'
#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')
target = today + os.sep + now + '.zip'
#Create the subdirectory if it isn't already there
if not os.path.exists(today):
#os.mkdir(today) #make single level directory
os.makedirs(today) #make multiple levels directory
print 'Successfully created directory',today
#5.We use the zip command to put the files in a zip archive
zip_command = "7z a -tzip %s %s" % (target,source)
#run the backup
if os.system(zip_command) == 0:
print 'Successful backup to',target
else:
print 'Backup Failed'
#End of file