Python 官方文档:入门教程 => 点击学习
光说不练假把式,用小脚本学习python。 一个简单的备份脚本。 #!/usr/bin/env python3 #-*- coding:utf-8 -*- #for backup import os import time #需要备份的目
光说不练假把式,用小脚本学习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')
--结束END--
本文标题: 用python备份文件
本文链接: https://www.lsjlt.com/news/184028.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0