Python实现备份文件实例
程序员文章站
2022-05-28 17:13:23
...
本文实例讲述了Python实现备份文件的方法,是一个非常实用的技巧。分享给大家供大家参考。具体方法如下:
该实例主要实现读取一个任务文件, 根据指定的任务参数自动备份.
任务文件的格式: (注意,分号后面注释是不支持的)
[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 sys import os import zipfile class 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希望本文所述对大家Python程序设计的学习有所帮助。