Python入门实战——文件压缩备份2.0(详解注释)

# 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')


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值