runksun 发表于 2013-10-8 09:17:57

[python]备份文件的一个小Demo

前些日子,看了一下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'


admin 发表于 2013-10-8 09:33:21

随手memo一下,以后备查,好习惯{:10_455:}

sunbao2010 发表于 2013-10-8 12:28:26

赞一个!好东西哈哈哈

antty 发表于 2013-10-8 19:06:49

学习下

阎魔あい 发表于 2013-10-10 00:01:53

技术贴~~~~~~~~~~~~~~~~~~
页: [1]
查看完整版本: [python]备份文件的一个小Demo