Python 实例: 备份文件

都说生命苦短,我用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代码:

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

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

原文地址:https://www.cnblogs.com/rrxc/p/4031005.html