脚本功能
- 备份某个目录
- 知识点:os模块、zipfile模块、配置文件、
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author MC.Lee
import zipfile
import os
import sys
import time
import configparser
from datetime import datetime
import re
class Back_file(object):
"""程序备份类"""
def __init__(self,path):
if os.path.exists(path):
self.path = os.path.abspath(path)
self.config = self.get_config()
self.re = self.__reIgnoreCompile()
else:
print('路径错误!')
exit()
def autoBack(self):
file_list = bf.getFileList()
self.createZip(file_list)
def get_config(self):
if not os.path.exists('config.ini'):
self.setDefaultConfig()
cfg = configparser.ConfigParser()
cfg.read('config.ini')
data = {}
for tag in cfg:
for key in cfg[tag]:
data[key] = cfg[tag][key]
return data
def setDefaultConfig(self):
data = {
"ignore":'log,tmp'
}
cfg = configparser.ConfigParser()
cfg['default'] = {}
cfg['default']["ignore"] = data["ignore"]
with open('config.ini','w') as cfgfile:
cfg.write(cfgfile)
def __reIgnoreCompile(self):
if self.config['ignore'].strip() == '':
return re.compile('\s')
# print('不忽略')
else:
extList = self.config['ignore'].split(',')
re_str = ''
for ext in extList:
ext = ext.strip()
re_str += f'(.*{ext}$)|'
re_str = re_str[:-1]
# print('忽略:',re_str)
re_fileext = re.compile(re_str)
return re_fileext
def checkIgnore(self,file_path):
if self.re.match(file_path):
return True
else:
return False
def getFileList(self):
for root, dirs, files in os.walk(self.path):
for name in files:
file_path = os.path.join(root, name)
if not self.checkIgnore(file_path):
yield file_path
def createZip(self,file_list):
zipFileName = f'{os.path.basename(self.path)}{datetime.now().strftime("%Y%m%d%H%M%S")}.zip'
my_zip = zipfile.ZipFile(zipFileName,'w')
for file_path in file_list:
my_zip.write(file_path,compress_type=zipfile.ZIP_DEFLATED)
print(f'写入文件:{file_path.replace(self.path,"")}')
my_zip.close()
if __name__ == '__main__':
path = r"D:\作业批改\test\51memo"
bf = Back_file(path)
bf.autoBack()