备份目录/文件
import zipfile
import os,datetime class beifen(object):
def __init__(self,files,new_files,compression=zipfile.ZIP_DEFLATED):
self.files = files
self.new_files = new_files
self.mode = ''
self.compression=compression
self.blo = self.has_file()
self.zhuluoji() def has_file(self):
if not os.path.exists(self.files):
raise EOFError("原文件不存在!")
else:
# print("源文件存在")
if os.path.isdir(self.files):
# print("源文件是目录")
return False
else:
# print("源文件是文件")
return True def has_new_files(self):
if not os.path.exists(self.new_files):
# print("目的地址文件不存在,直接备份")
self.mode = 'w'
else:
# print("目的地址文件存在,追加备份")
self.mode = 'a'
# self.new_files = datetime.datetime.now().strftime('%Y-%m-%d') + "-" +self.new_files+ '.zip'
dirname = os.path.dirname(self.new_files)
basename = os.path.basename(self.new_files)
self.new_files = dirname + r'\\' + datetime.datetime.now().strftime('%Y-%m-%d') +" "+ basename +'.zip'
print(self.new_files) def zipfile(self,blo):
with zipfile.ZipFile(self.new_files, self.mode, self.compression) as z:
print("正在执行备份操作.....请稍后.......")
if blo:
z.write(self.files)
else:
for i1,i2,i3 in os.walk(self.files):
for x in i3:
z.write(os.path.join(i1,x))
print("备份成功!") def zhuluoji(self):
self.has_new_files()
if self.blo:
self.zipfile(self.blo)
else:
self.zipfile(self.blo) if __name__=='__main__':
print(r"""
files = 路径\源文件名.文件类型 or 路径\源文件目录;
new_files = 绝对-相对路径\文件名;
""")
files = input("输入源文件路径")
new_files = input("输入目的文件路径")
bf = beifen(r"D:\aaa\JetbrainsCrack-2.8-release-enc.jar",r'D:\bbb\备份')