# 2.0版本新增功能:1、判断文件是否存在 2、以时间作为文件名,存储在当前日期为名字的文件夹
# 3、将文件修改与zip文件的文件名产生关联, 通过将用户提供的注释内容添加到文件名中来实现。
import os
import time
source=['D:\\test\\q.txt','D:\\test\\w.txt']
#1、判断文件是否存在
if os.path.exists(''.join(source)):
message='The "%s" file exists'
else:
#print('can not found files')
message='cannot find the "%s" file'
print(message % source)
target_dir='D:\\testr'#主备份目录
#如果目标目录不存在则创建目录,Windows下可以忽略这部分,因为能自动创建
#if not os.path.exists(target_dir):
# os.mkdir(target_dir)
#2、将当前日期作为主备份目录下的子目录
today = target_dir + os.sep + time.strftime('%Y%m%d')
#将当前时间作为zip文件的文件名
now=time.strftime('%H%M%S')
#3、添加一条来自用户的注释以创建zip文件名
annotation=input('Enter a annotation-->')
#检查是否有注释键入
if len(annotation)==0:
target=today + os.sep + now + '.zip'#没有注释直接打包
else:
target=today + os.sep + now +'_'+ annotation +'_'+'.zip'#有注释,在结尾插入
#如果目标目录不存在则创建目录,Windows下不要这部分,因为能自动创建且重复创建会报错
if not os.path.exists(today):
print('原本没有此目录')
# os.mkdir('today')
# print('successfully created directory',today)
#使用压缩软件7-Zip的压缩命令 7z a(添加) ;7z a -r(添加并递归子目录)
zip_command='7z a {} {}'.format(target,' '.join(source))
print(zip_command)
if os.system(zip_command)==0:
print ('Successful backup to',target )
else:
print( 'Backup FAILED' )
print('Done')