《a byte of python》学习笔记:windows下实现备份的python脚本

《a byte of python》第十章里的例子
作者简单的说到:我们使用标准的zip命令,它通常默认地随Linux/Unix发行版提供。Windows用户可以使用Info-Zip程序。注意你可以使用任何地存档命令,只要它有命令行界面就可以了,那样的话我们可以从我们的脚本中传递参数给它。

但具体怎么做呢?

其实,用windows系统中常用的WinRar就可以实现。

除了图形界面,WinRar也是可以用命令行参数来进行压缩文件。

例如我要实现将D:\yan\python下的1.txt压缩到同目录下的rar.rar文件,则在命令行中输入:
C:\progra~1\WinRAR\Rar.exe a -m5 D:\yan\python\rar.rar D:\yan\python\1.txt
回车即可得到所要结果

progra~1即代表Program Files,之所与这样表示,是因为文件名的8.3格式:较旧的Windows操作系统或DOS的档案命名限制,
8指档案名称最大长度为8
3指副档名称最大长度为3
若不符合以上限制则会以"~"作延长名称如"Program Files"会变成"Progra~1"
若同一资料夹有相似的名称,末端的数值则会自动递增。

如果想直接使用rar命令,而不是繁琐的C:\progra~1\WinRAR\Rar.exe,则要在path环境变量里添加C:\Program Files\WinRAR

此时输入:
rar a -m5 D:\yan\python\rar.rar D:\yan\python\1.txt
即可以得到想要的结果。

我们现在可以开始写python脚本了,下面是我已经实现的第一个脚本:

# Filename: backup_ver1.py

import os
import time

# 1. The files and directories to be backed up are specified in a list.
source = ['D:\\yan\\python']
# 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 = 'D:\\yan\\python\\' # 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= "rar a -r %s %s"%(target,''.join(source))

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

备份脚本的版本二:

import os
import time

source = [r'D:\workspace1\TestThread']
target_dir = 'D:\workspace1\python\\'

today = target_dir + time.strftime('%Y%m%d')

now = time.strftime('%H%M%S')

if not os.path.exists(today):
    os.mkdir(today)
    print 'Successfully created directory', today

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

zip_command = "rar a -r %s %s" % (target, ' '.join(source))

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

最后的版本:

import os
import time

source = [r'D:\workspace1\testsun']

target_dir = 'D:\workspace1\python\\'

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 + '.zip'
else:
    target = today + os.sep + now + '_' + \
        comment.replace(' ', '_') + '.zip'

zip_command = "rar a -r %s %s" % (target, ''.join(source))

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值