python在windows下创建备份程序__简明 Python 教程

备份脚本:版本一
#coding=utf-8

import os
import time

source = 'F:\\1'
target_dir = r'F:\3\\'

target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.rar'

rar_command =r'"D:\Program Files\WinRAR\WinRAR.exe" a %s %s' % (target,source)
# a  添加文件到压缩文件
if os.system(rar_command) == 0:
    print 'Successful backup to', target
else:
    print 'Backup FAILED'

注:将文件夹F:\\1压缩备份到 F:\3\\中;D:\Program Files\WinRAR\WinRAR.exe改成自己相应的WinRAR的安装目录;

备份脚本:版本二
#coding=utf-8

import os
import time

source = ['F:\\1','F:\\2']

target_dir = 'F:\\3\\'

today = target_dir + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')

if not os.path.exists(today):
    os.mkdir(today)
    print 'yes',today
#如果path存在,返回True;如果path不存在,返回False。
#改变的部分主要是使用os.exists函数检验在主备份目录中是否有以当前日期作为名称的目录。如果没有,我们使用os.mkdir函数创建。
target = today + os.sep + now + '.rar'
#注意os.sep变量的用法——这会根据你的操作系统给出目录分隔符,即在Linux、Unix下它是'/',在Windows下它是'\\',而在Mac OS下它是':'。使用os.sep而非直接使用字符,会使我们的程序具有移植性,可以在上述这些系统下工作。
rar_command = r'"D:\Program Files\WinRAR\WinRAR.exe " a %s %s  ' % (target,' '.join(source))

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

备份脚本:版本三(四)
#coding=utf-8

import os
import time

source = ['F:\\1','F:\\2']

target_dir = 'F:\\3\\'

today = target_dir + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')
comment = raw_input('Enter a comment -->')

if len(comment) == 0:
    target = today + os.sep + now + '.rar'
else:
    target = today + os.sep + now + '_' + \
    comment.replace(' ','_') + '.rar'
#str.replace(old, new[, max])
#max:用来替换的次数,这里有两种:(1)当不将max参数传入时,默认将所有old字符或者字符串替换为new字符或者字符串;(2)当我们将max参数传入后,则将旧字符串替换为新字符串不超过max次,多余的则不进行替换
#str = "bbbbaaabbbbaabbaabbaa"
#print(str.replace('a', '+'))
#print(str.replace('a', '+', 3))
# 输出:
# bbbb+++bbbb++bb++bb++
# bbbb+++bbbbaabbaabbaa
#有的系统中文件命名中不能有空格
if not os.path.exists(today):
    os.mkdir(today)
    print 'yes',today
#如果path存在,返回True;如果path不存在,返回False。
#改变的部分主要是使用os.exists函数检验在主备份目录中是否有以当前日期作为名称的目录。如果没有,我们使用os.mkdir函数创建。
#注意os.sep变量的用法——这会根据你的操作系统给出目录分隔符,即在Linux、Unix下它是'/',在Windows下它是'\\',而在Mac OS下它是':'。使用os.sep而非直接使用字符,会使我们的程序具有移植性,可以在上述这些系统下工作。
rar_command = r'"D:\Program Files\WinRAR\WinRAR.exe " a %s %s  ' % (target,' '.join(source))

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

猜你喜欢

转载自blog.csdn.net/hhyiyuanyu/article/details/79632922
今日推荐