python脚本案例---备份单个目录

#!/bin/python
#coding:utf-8

import os
import time

############################
# 备份单个目录指定在列表中
############################
source = ['/usr/apps/config/']
# source = [r'"C:\Test file"', 'C:\Code'] #若有空格,则必须再次用引号括起来;双反斜杠转义序列,你还可以使用原始字符串。例如使用 'C:\\Documents' 或 r'C:\Documents' 。

# 指定主备份目录
target_dir = '/usr/apps/backup'
# target_dir = 'E:\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)) #打包文件;字符串方法 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')

 

执行脚本效果:

 

posted on 2020-09-03 07:27  chalon  阅读(101)  评论(0编辑  收藏  举报