都说生命苦短,我用python, 所以这两天我也开始学python了.

昨天搞了下语法,今天搞出来个实例,备份文件.尽管编码相当烂,但是测试了一下,还真能用.

它读取一个任务文件, 根据指定的任务参数自动备份.

任务文件的格式: (注意,分号后面注释是不支持的)

  1. [task]  ; 一项任务开始
  2. dir=h:/Project  ; 指定备份的目录
  3. recusive=1      ; 是否递归子目录
  4. suffix=h|cpp|hpp|c|user|filters|vcxproj|sln|css|gif|html|bmp|png|lib|dsw|dsp|htm|html|ico|ini|jpg|rc|vssscc ; 指定备份的扩展名
  5. exclude=0   ; 指定是备份上面的参数指定的扩展名还是排除指定的扩展名
  6. zip=Project.zip ; 备份后的文件路径名

这是python代码:

  1. # -*- coding: utf-8 -*-
  2. import sys
  3. import os
  4. import zipfile
  5. class Task:
  6. #dir str directory
  7. #bsub BOOL include subdirectory
  8. #sfx str postsuffix ,sepeated by '|'
  9. #ecld BOOL include or execlude the postsuffix sfx
  10. def __init__(self,dir,bsub,sfx,ecld,zip):
  11. self.dir = dir
  12. self.bsub = bsub
  13. self.suffix = sfx.split("|")
  14. self.exclude = ecld
  15. self.zip = zip
  16. @staticmethod
  17. def isfilter(sfx,sfxs,bexcld):
  18. bFound = False
  19. for e in sfxs:
  20. if e == sfx:
  21. bFound = True
  22. break
  23. if bexcld:
  24. return not bFound;
  25. else:
  26. return bFound;
  27. class QBackup:
  28. '''''备份指定目录下具备指定扩展名的文件'''
  29. def __init__(self):
  30. self._list = []
  31. def __del__(self):
  32. pass
  33. #tfile 任务文件
  34. def ReadTask(self,tfile):
  35. dir = ""
  36. bsub = False
  37. sfx = ""
  38. becld = False
  39. zip = ""
  40. try:
  41. f = open(tfile,'r')
  42. while True:
  43. line = f.readline()
  44. if len(line) == 0:
  45. break;
  46. line = line.strip(" ")
  47. if "[Task]/n".lower() == line.lower():
  48. # 读取接下来的4行
  49. iline = 1
  50. while iline <= 5:
  51. line = f.readline()
  52. line = line.strip(" /t/n")  # 去除前后的空白符
  53. idx = line.find("=")
  54. if -1 == idx:
  55. break;
  56. atti = line[0:idx]
  57. value = line[idx+1:]
  58. print(value)
  59. if "dir" == atti:
  60. dir = value
  61. elif "recusive" == atti:
  62. bsub = bool(int(value))
  63. elif "suffix" == atti:
  64. sufix = value
  65. elif "exclude" == atti:
  66. becld = bool(int(value))
  67. elif "zip" == atti:
  68. zip = value
  69. else:
  70. break
  71. iline += 1
  72. else:
  73. t = Task(dir,bsub,sufix,becld,zip)
  74. self._list.append(t)
  75. except:
  76. return False
  77. return True
  78. def DoBackup(self):
  79. for e in self._list:
  80. try:
  81. zip = zipfile.ZipFile(e.zip,'w',zipfile.ZIP_DEFLATED)
  82. self.ZipDir(zip,e.dir,e.bsub,e.suffix,e.exclude)
  83. zip.close()
  84. except:
  85. print("exception raised!")
  86. return False
  87. return True
  88. def ZipDir(self,zip,dir,bsub,sfxs,ecld):
  89. subdir = ""
  90. path = ""
  91. if os.path.isdir(dir):
  92. paths = os.listdir(dir)
  93. #备份本目录
  94. print("ZipDir: ",dir)
  95. for e in paths:
  96. path = dir + "/" + e
  97. ext = os.path.splitext(e)[1][1:]
  98. if os.path.isfile(path) and Task.isfilter(ext,sfxs,ecld):
  99. print ("ZipFile: ",path)
  100. zip.write(path)
  101. #清理子目录
  102. if bsub:
  103. for e in paths:
  104. subdir = dir + "/" + e
  105. self.ZipDir(zip,subdir,bsub,sfxs,ecld)
  106. def PrintTask(self):
  107. for e in self._list:
  108. print (e.dir,e.bsub,e.suffix,e.exclude,e.zip)
  109. if '__main__' == __name__:
  110. c = QBackup()
  111. c.ReadTask("bkup.txt")
  112. c.DoBackup()

用python写小应用的确很爽啊!C++就太笨重了!

Python 实例: 备份文件的更多相关文章

  1. 第一个python实例--监控cpu

    #第一个python实例:监控cpu #/bin/bash/env Python from __future__ import print_function from collections impo ...

  2. (转)Python实例手册

    原文地址:http://hi.baidu.com/quanzhou722/item/cf4471f8e23d3149932af2a7 实在是太好的资料了,不得不转 python实例手册 #encodi ...

  3. 使用docker安装部署Spark集群来训练CNN(含Python实例)

    使用docker安装部署Spark集群来训练CNN(含Python实例) http://blog.csdn.net/cyh_24/article/details/49683221 实验室有4台神服务器 ...

  4. 【NLP】Python实例:申报项目查重系统设计与实现

    Python实例:申报项目查重系统设计与实现 作者:白宁超 2017年5月18日17:51:37 摘要:关于查重系统很多人并不陌生,无论本科还是硕博毕业都不可避免涉及论文查重问题,这也对学术不正之风起 ...

  5. 转载 python实例手册

    python实例手册 #encoding:utf8# 设定编码-支持中文 0说明 手册制作: 雪松 更新日期: 2013-12-19 欢迎系统运维加入Q群: 198173206 # 加群请回答问题 请 ...

  6. 【NLP】Python实例:基于文本相似度对申报项目进行查重设计

    Python实例:申报项目查重系统设计与实现 作者:白宁超 2017年5月18日17:51:37 摘要:关于查重系统很多人并不陌生,无论本科还是硕博毕业都不可避免涉及论文查重问题,这也对学术不正之风起 ...

  7. python实例、类方法、静态方法

    [python实例.类方法.静态方法] 参考:http://blog.163.com/yang_jianli/blog/static/161990006201122411586729/

  8. 【转载】python实例手册

    今天写爬虫的时候遇到了问题,在网上不停地查找资料,居然碰到两篇好文章: 1.python实例手册   作者:没头脑的土豆 另一篇在这:shell实例手册 python实例手册 #encoding:ut ...

  9. Python实例---利用正则实现计算器[FTL版]

    import re # 格式化 def format_str(str): str = str.replace('--', '+') str = str.replace('-+', '-') str = ...

随机推荐

  1. hdu 3863 No Gambling

    #include<stdio.h> int main() { int n; ) { printf("I bet on Oregon Maple~\n"); } ; } ...

  2. android MD5

    public static String MD5(String str) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstan ...

  3. *windows文件显示后缀名

  4. PCL—低层次视觉—点云滤波(基于点云频率)

    1.点云的频率 今天在阅读分割有关的文献时,惊喜的发现,点云和图像一样,有可能也存在频率的概念.但这个概念并未在文献中出现也未被使用,谨在本博文中滥用一下“高频”一词.点云表达的是三维空间中的一种信息 ...

  5. linux查看硬件环境

    一:查看cpu more /proc/cpuinfo | grep "model name" grep "model name" /proc/cpuinfo 如 ...

  6. openfire的smack和asmack

    smack你可以看成是一套封装好了的用于实现XMPP协议传输的API,它是一个非常简单并且功能强大的类库,给用户发送消息只需要三行代码.下载地址:http://www.igniterealtime.o ...

  7. cocos2dx 的基本框架

    AppDelegate.h #ifndef _APP_DELEGATE_H_ #define _APP_DELEGATE_H_ #include "cocos2d.h" USING ...

  8. centos防火墙设置

    1.查看 service iptables status 2.开关 service iptables start/stop 3.开机启动 chkconfig iptables on/off 4.编辑端 ...

  9. linux 命令学习大全

    转载  http://blog.csdn.net/xiaoguaihai/article/details/8705992/

  10. Regex Failure - Bug Fixing #2

    http://www.codewars.com/kata/55c423ecf847fbcba100002b/train/csharp Oh no, Timmy's received some hate ...