Python简明教程之一键备份

Python简明教程之一键备份
文章图片
image.png

问题:Linux和Windows下一键压缩多个文件
要求如下:
1.需要备份的文件和目录由一个列表指定
2.备份应该保存在主备份目录中
3.文件备份成一个zip文件
4.zip存档的名称是当时的日期和时间
5.我们用标准的zip命令,它通常默认地随Linux/Unix发行提供。Windows用户可用Info-Zip程序。
【Python简明教程之一键备份】脚本如下:
# -*- coding:utf-8 -*- #Filename:backup_ver3.pyimport os import time#1.The first and directories to be backed up are specified in a list source = ['/home/kanshan/Desktop/python_demon','/home/kanshan/Desktop/site' ] #If you are using WIndows, use source = [r'C:\Documents', r'D:\Work'] or something like that#2.The backup must be stored in a main backup directory target_dir = '/home/kanshan/Desktop/'#3.The files are backed up into a zip file #4.The current day is the name of the subdirectory in the main directory today = target_dir + time.strftime('%Y%m%d') #The current time is the name of the zip archieve now = time.strftime('%H%M%S')#Take a comment from the user to creat the name of the zip file comment = input("Enter a comment -->") print(len(comment)) if len(comment) == 0: target = today + os.sep + now + '.zip' else: target = today + os.sep + now + '_' + comment.replace(' ','_') + '.zip'#Create the subdirectory if it is not already there if not os.path.exists(today): os.mkdir(today)#make directory print("Sucessful created directory",today)#5.We use the zip command (in Linux/Unix) to put the files in a zip archive zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))#Run the backup if os.system(zip_command) == 0: print ( "Successful backup to",target ) else: print ( "Backup Failed" )

运行结果如下

Python简明教程之一键备份
文章图片
文件目录备份.png

    推荐阅读