该实例主要实现读取一个任务文件, 根据指定的任务参数自动备份.
任务文件的格式: (注意,分号后面注释是不支持的)
[task] ; 一项任务开始dir=h:/project ; 指定备份的目录recusive=1 ; 是否递归子目录suffix=h|cpp|hpp|c|user|filters|vcxproj|sln|css|gif|html|bmp|png|lib|dsw|dsp|htm|html|ico|ini|jpg|rc|vssscc ; 指定备份的扩展名exclude=0 ; 指定是备份上面的参数指定的扩展名还是排除指定的扩展名zip=project.zip ; 备份后的文件路径名
python代码如下:
# -*- coding: utf-8 -*- import sysimport osimport zipfileclass task: #dir str directory #bsub bool include subdirectory #sfx str postsuffix ,sepeated by '|' #ecld bool include or execlude the postsuffix sfx def __init__(self,dir,bsub,sfx,ecld,zip): self.dir = dir self.bsub = bsub self.suffix = sfx.split(|) self.exclude = ecld self.zip = zip @staticmethod def isfilter(sfx,sfxs,bexcld): bfound = false for e in sfxs: if e == sfx: bfound = true break if bexcld: return not bfound; else: return bfound; class qbackup: '''备份指定目录下具备指定扩展名的文件''' def __init__(self): self._list = [] def __del__(self): pass #tfile 任务文件 def readtask(self,tfile): dir = bsub = false sfx = becld = false zip = try: f = open(tfile,'r') while true: line = f.readline() if len(line) == 0: break; line = line.strip( ) if [task]/n.lower() == line.lower(): # 读取接下来的4行 iline = 1 while iline <= 5: line = f.readline() line = line.strip( /t/n) # 去除前后的空白符 idx = line.find(=) if -1 == idx: break; atti = line[0:idx] value = line[idx+1:] print(value) if dir == atti: dir = value elif recusive == atti: bsub = bool(int(value)) elif suffix == atti: sufix = value elif exclude == atti: becld = bool(int(value)) elif zip == atti: zip = value else: break iline += 1 else: t = task(dir,bsub,sufix,becld,zip) self._list.append(t) except: return false return true def dobackup(self): for e in self._list: try: zip = zipfile.zipfile(e.zip,'w',zipfile.zip_deflated) self.zipdir(zip,e.dir,e.bsub,e.suffix,e.exclude) zip.close() except: print(exception raised!) return false return true def zipdir(self,zip,dir,bsub,sfxs,ecld): subdir = path = if os.path.isdir(dir): paths = os.listdir(dir) #备份本目录 print(zipdir: ,dir) for e in paths: path = dir + / + e ext = os.path.splitext(e)[1][1:] if os.path.isfile(path) and task.isfilter(ext,sfxs,ecld): print (zipfile: ,path) zip.write(path) #清理子目录 if bsub: for e in paths: subdir = dir + / + e self.zipdir(zip,subdir,bsub,sfxs,ecld) def printtask(self): for e in self._list: print (e.dir,e.bsub,e.suffix,e.exclude,e.zip) if '__main__' == __name__: c = qbackup() c.readtask(bkup.txt) c.dobackup()
希望本文所述对大家python程序设计的学习有所帮助。
