windows平台下实现《简明python教程》第10章的文件备份示例四

 参考一《简明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

运行结果:



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值