python备份文件

来源:互联网 发布:淘宝首页广告位价格 编辑:程序博客网 时间:2024/06/10 02:22

  

转载:http://zhouyangchenrui.iteye.com/blog/682143

python备份文件的例子在windows下采用winrar的rar命令运行可以成功,只是要有winrar软件和设置其环境变量。 

Java代码  收藏代码
  1. # Filename: backup_ver4.py  
  2. import os  
  3. import time  
  4.   
  5. 1.需要备份的文件目录  
  6. source = ['F:\\python\\code']  
  7.   
  8. 2. 备份文件到目标路径  
  9. target_dir = 'F:\\python\\backup\\'  
  10.   
  11. 3. The files are backed up into a zip file.  
  12. 4. The current day is the name of the subdirectory in the main directory  
  13. today = target_dir + time.strftime('%Y%m%d')  
  14. # The current time is the name of the zip archive  
  15. now = time.strftime('%H%M%S')  
  16.   
  17. # Take a comment from the user to create the name of the zip file  
  18. comment = raw_input('Enter a comment -->')  
  19. if len(comment)==0:   
  20.     target = today+os.sep+now+'.zip'  
  21. else:  
  22.     target = today+os.sep+now+'_'+\  
  23.              comment.replace(' ','_')+'.zip'  
  24.     # Notice the backslash!  
  25.   
  26. # Create the subdirectory if it isn't already there  
  27. if not os.path.exists(today):  
  28.     os.mkdir(today)  # make directory  
  29.     print('Successfully created directory', today)  
  30.   
  31. 5. 用winrar的rar命令压缩文件,但首先要安装有winrar且设置winrar到环境变量的路径path中  
  32. zip_command = "rar a %s %s" %(target,''.join(source))  
  33.   
  34. # Run the backup  
  35. #设置winrar到path环境中,这里已经手动添加,如图  
  36. #os.system('set Path=%Path%;C:\Program Files\WinRAR')  
  37. if os.system(zip_command)==0:  
  38.     print('Successful backup to', target)  
  39. else:  
  40.     print('Backup FAILED')  

设置winrar环境变量如下图: 
原创粉丝点击