用python備份文件

光說不練假把式,用小腳本學習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')


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章