Python implements backup file instances

  • 2020-04-02 14:03:56
  • OfStack

This article illustrates how Python implements backup files, which is a very useful technique. Share with you for your reference. Specific methods are as follows:

This instance mainly realizes reads a task file, according to the specified task parameter automatic backup.

Task file format: (note that comments after semicolons are not supported)


[task] ;  A mission begins 
dir=h:/Project ;  Specify the directory to backup 
recusive=1 ;  Whether recursive subdirectories 
suffix=h|cpp|hpp|c|user|filters|vcxproj|sln|css|gif|html|bmp|png|lib|dsw|dsp|htm|html|ico|ini|jpg|rc|vssscc ;  Specifies the extension for the backup 
exclude=0 ;  Specifies whether to back up the extension specified by the above argument or to exclude the specified extension 
zip=Project.zip ;  File path name after backup 

The python code is as follows:


# -*- 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:
 ''' Backup files with the specified extension in the specified directory '''
 def __init__(self):
 self._list = []
 
 def __del__(self):
 pass
 
 #tfile  Task file 
 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():
   #  Read the following 4 line 
   iline = 1
   while iline <= 5:
   line = f.readline()
   line = line.strip(" /t/n") #  Before and after whitespace is removed  
   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)
  # Backup this directory 
  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)
  # Clean up subdirectories 
  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()
 

I hope that this article has helped you to learn Python programming.


Related articles: