使用python在windows 下 编写 自动备份脚本

来源:互联网 发布:python 行为树 实现 编辑:程序博客网 时间:2024/05/17 01:08

本人刚刚学习编写python  通过简明的Python 教程在学习。为了能够学习的比较透测,就将简明教程里面的在linux 上面第十章的例子改用windows 下编写。

下面是在linux下编写脚本的例子:

例10.1 备份脚本——版本一

#!/usr/bin/python
# Filename: backup_ver1.py


import os
import time

# 1. The files and directories to be backed up are specified in a list.
source = ['/home/swaroop/byte', '/home/swaroop/bin']
# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that

# 2. The backup must be stored in a main backup directory

target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using

# 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time

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

# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target,' '.join(source))

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

我在windows下备份的例子是这么写的:

#导入os和time模块

import os
import time

#申明 source 列表
source = [r'C:\Users\wuhuhuan\Desktop\lxh',"C:\\Users\\wuhuhuan\\Desktop\\"]

#定义today 变量
today=source[1]+time.strftime('%Y%m%d')
#用判断 是否存在当前年月日的文件夹如果不存在创建文件夹并打印输出
if not os.path.exists(today):
    os.mkdir(today)
    print 'Successfully created directory',today

#定义now 当前时间
now = today+'\\'
target=now+time.strftime('H%M%S')+'.rar'
zip_command= 'winrar a %s %s -r' %(target,''.join(source[0]))

#通过os.system命令打开cmd 执行 压缩命令
if os.system(zip_command) == 0:
    print 'Successful backup to',target
else:
    print 'Backup Failed'


这个例子是Users\wuhuhuan\Desktop路径下有个文件夹 lxh  。在windows 系统dos 里面执行的命令是  winrar a  要将文件保存的名称(可以带路径) 要压缩的路径 -r 

具体看代码注释。本人刚刚接触python 请多多指教。


0 0
原创粉丝点击