[技术| 编程·课件·Linux] [python]备份文件的一个小Demo

runksun · 发布于 2013-10-08 09:17 · 1181 次阅读
2461
前些日子,看了一下python,修改了一个小例子共享下,(整体代码是从网上复制下来的,但是运行的时候,总是会报错,增加了rar命令的路径和rar 的命令,使该问题得到了解决)大神勿喷:说明:Windows环境下将D盘的documents\python目录被分到F盘python\backup文件夹下:

#-*-coding:UTF-8 -*-
'''
@author: runksun
@author_mail: runksun@*******
Created :2013年10月5日
'''

# Filename: backup_ver4.py  
import os  
import time  

# 1.需要备份的文件目录  
source = ['D:\\documents\\python']  

# 2. 备份文件到目标路径  
target_dir = 'F:\\python\\backup\\'  

# 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')  

# Take a comment from the user to create the name of the zip file  
'''comment = input('Enter a comment -->')  
if len(comment)==0:   
    target = today+os.sep+now+'.zip'  
else:  
    target = today+os.sep+now+'_'+\
             comment.replace(' ','_')+'.zip'  
'''   # Notice the backslash!  

target=today+os.sep+now+'.zip'



print target
# Create the subdirectory if it isn't already there  
if not os.path.exists(today):  
    print 'running in mkdir'
    os.mkdir(today)  # make directory  
    print('Successfully created directory', today)  

# 5. 用winrar的rar命令压缩文件,但首先要安装有winrar且设置winrar到环境变量的路径path中  

print 'the two strings are %s and %s'%(target,''.join(source))
#这里需要添加rar的绝对路径,即使配置了环境,还是无法执行rar命令
zip_command = '"C:\\Program Files\\WinRAR\\rar.exe" a -r %s %s' %(target,''.join(source))  


print zip_command
if os.system(zip_command)==0:  
    print('Successful backup to', target)  
else:  
    print('Backup FAILED')

print 'this program ended'


评分

参与人数 1学分 +20 收起 理由
小马 + 20 很给力!

查看全部评分

共收到 4 条回复
admin · #2 · 2013-10-8 09:33:21  回复 支持 反对
随手memo一下,以后备查,好习惯
sunbao2010 · #3 · 2013-10-8 12:28:26  回复 支持 反对
赞一个!好东西哈哈哈
antty · #4 · 2013-10-8 19:06:49  回复
学习下
阎魔あい · #5 · 2013-10-10 00:01:53  回复
技术贴~~~~~~~~~~~~~~~~~~
回帖
B Color Image Link Quote Code Smilies
Command + Enter
快速回复 返回顶部 返回列表