脚本功能

  • 备份某个目录
  • 知识点:os模块、zipfile模块、配置文件、
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # author MC.Lee
  4. import zipfile
  5. import os
  6. import sys
  7. import time
  8. import configparser
  9. from datetime import datetime
  10. import re
  11. class Back_file(object):
  12. """程序备份类"""
  13. def __init__(self,path):
  14. if os.path.exists(path):
  15. self.path = os.path.abspath(path)
  16. self.config = self.get_config()
  17. self.re = self.__reIgnoreCompile()
  18. else:
  19. print('路径错误!')
  20. exit()
  21. def autoBack(self):
  22. file_list = bf.getFileList()
  23. self.createZip(file_list)
  24. def get_config(self):
  25. if not os.path.exists('config.ini'):
  26. self.setDefaultConfig()
  27. cfg = configparser.ConfigParser()
  28. cfg.read('config.ini')
  29. data = {}
  30. for tag in cfg:
  31. for key in cfg[tag]:
  32. data[key] = cfg[tag][key]
  33. return data
  34. def setDefaultConfig(self):
  35. data = {
  36. "ignore":'log,tmp'
  37. }
  38. cfg = configparser.ConfigParser()
  39. cfg['default'] = {}
  40. cfg['default']["ignore"] = data["ignore"]
  41. with open('config.ini','w') as cfgfile:
  42. cfg.write(cfgfile)
  43. def __reIgnoreCompile(self):
  44. if self.config['ignore'].strip() == '':
  45. return re.compile('\s')
  46. # print('不忽略')
  47. else:
  48. extList = self.config['ignore'].split(',')
  49. re_str = ''
  50. for ext in extList:
  51. ext = ext.strip()
  52. re_str += f'(.*{ext}$)|'
  53. re_str = re_str[:-1]
  54. # print('忽略:',re_str)
  55. re_fileext = re.compile(re_str)
  56. return re_fileext
  57. def checkIgnore(self,file_path):
  58. if self.re.match(file_path):
  59. return True
  60. else:
  61. return False
  62. def getFileList(self):
  63. for root, dirs, files in os.walk(self.path):
  64. for name in files:
  65. file_path = os.path.join(root, name)
  66. if not self.checkIgnore(file_path):
  67. yield file_path
  68. def createZip(self,file_list):
  69. zipFileName = f'{os.path.basename(self.path)}{datetime.now().strftime("%Y%m%d%H%M%S")}.zip'
  70. my_zip = zipfile.ZipFile(zipFileName,'w')
  71. for file_path in file_list:
  72. my_zip.write(file_path,compress_type=zipfile.ZIP_DEFLATED)
  73. print(f'写入文件:{file_path.replace(self.path,"")}')
  74. my_zip.close()
  75. if __name__ == '__main__':
  76. path = r"D:\作业批改\test\51memo"
  77. bf = Back_file(path)
  78. bf.autoBack()

backup备份工具 - 图1