参考一《简明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
运行结果: