版权声明:欢迎转载!如有纰漏之处,欢迎批评指正! https://blog.csdn.net/black_kyatu/article/details/81838807
编写python脚本实现压缩备份功能。
示例代码:
运行环境:linux
import os
import time
source = ['/home/es-pc/Desktop/test']
#需要备份的文件夹
target_dir = '/home/es-pc/Desktop/backup'
#存放备份的文件夹
target = target_dir + os.sep + \
time.strftime('%Y%m%d%H%M%S') + '.zip'
#备份文件命名
if not os.path.exists(target_dir):
os.mkdir(target_dir)
#备份文件夹不存在时创建文件夹
zip_command = 'zip -r {0} {1}'.format(target,' '.join(source))
#zip压缩命令
print('Zip command is:')
print(zip_command)
print('Running:')
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')
不足之处:
- 路径有空格时zip命令不能正确执行
- 备份文件过多时不易区分整理
改进:将备份文件按日期分文件夹保存,并对每个备份文件文件名加上备注
改进后的代码:
import os
import time
source = ['/home/es-pc/Desktop/te st']
target_dir = '/home/es-pc/Desktop/back up'+os.sep +\ time.strftime('%Y%m%d')
name = input('INPUT NAME OF BACKUP:\n')
if len(name)!=0:
target = target_dir + os.sep + \
time.strftime('%H%M%S') + '_'+name+'.zip'
else:
target = target_dir + os.sep + \
time.strftime('%Y%m%d%H%M%S') + '.zip'
if not os.path.exists(target_dir):
os.mkdir(target_dir)
zip_command = 'zip -r "{0}" "{1}"'.format(target,' '.join(source))
print('Zip command is:')
print(zip_command)
print('Running:')
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')