前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >用python备份文件

用python备份文件

作者头像
py3study
发布2020-01-14 14:57:41
1.3K0
发布2020-01-14 14:57:41
举报
文章被收录于专栏:python3python3
代码语言:javascript
复制
光说不练假把式,用小脚本学习Python。
一个简单的备份脚本。

#!/usr/bin/env python3
#-*- coding:utf-8 -*-
#for backup
import os
import time
#需要备份的目录
source = ['/var/log/history/','/var/log/httpd/']
#保存备份的目录
target_dir = '/tmp/'
today_dir = target_dir + time.strftime('%Y%m%d')
time_dir = time.strftime("%H%M%S")
'''
os.sep:主要是为了跨平台,根据系统的不同,分隔符不一样
>>> os.sep
'/'
'''
touch  = today_dir  + os.sep + time_dir + '.zip'
print(touch)
'''
zip :
	-q:执行时不显示压缩过程
	-r:对该目录递归
' '.join(source):将列表转换位字符串
	>>> sou = ['s','y','l']
	>>> s = ' '.join(sou)
	>>> print(s)
	s y l
'''
zip_command = "zip -qr " + touch + ' ' + ' '.join(source)
print(zip_command)
'''
将target、source及“ zip -qr ”通过字符串连接符号相连接,得到command命令行,再调用os.system()函数运行command命令,如果成功,返回0,否则返回错误号
os.path.exits():exits()函数的功能就是检查该系统中,是否存在指定路径的文件或文件夹存,没有返回False(False 等于 0),有则返回True(True 不等于 0)
>>> os.path.exists('/')
True
>>> os.path.exists('/true')
False
'''
if os.path.exists(today_dir)==0:
	os.mkdir(today_dir)
if os.system(zip_command) == 0:
	print('Successful backup')
else:
	print('Backup Failed')
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-07-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档