使用python在windows 下 編寫 自動備份指令碼
本人剛剛學習編寫python 通過簡明的Python 教程在學習。為了能夠學習的比較透測,就將簡明教程裡面的在linux 上面第十章的例子改用windows 下編寫。
下面是在linux下編寫指令碼的例子:
#!/usr/bin/python
# Filename: backup_ver1.pyimport
os
import
time
# 1. The files and directories to be backed up are specified in a list.
source = [
'/home/swaroop/byte'
,
'/home/swaroop/bin'
]
# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that
# 2. The backup must be stored in a main backup directory
target_dir =
'/mnt/e/backup/'
# Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time
target = target_dir +
time
.strftime(
'%Y%m%d%H%M%S'
) +
'.zip'
# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command =
"zip -qr '%s' %s"
% (target,
' '
.join(source))
# Run the backup
if
os
.system(zip_command) ==
0
:
print
'Successful backup to'
, target
else
:
print
'Backup FAILED'
我在windows下備份的例子是這麼寫的:
#匯入os和time模組
import os
import time
#申明 source 列表
source = [r'C:\Users\wuhuhuan\Desktop\lxh',"C:\\Users\\wuhuhuan\\Desktop\\"]
#定義today 變數
today=source[1]+time.strftime('%Y%m%d')
#用判斷 是否存在當前年月日的資料夾如果不存在建立資料夾並列印輸出
if not os.path.exists(today):
os.mkdir(today)
print 'Successfully created directory',today
#定義now 當前時間
now = today+'\\'
target=now+time.strftime('H%M%S')+'.rar'
zip_command= 'winrar a %s %s -r' %(target,''.join(source[0]))
#通過os.system命令開啟cmd 執行 壓縮命令
if os.system(zip_command) == 0:
print 'Successful backup to',target
else:
print 'Backup Failed'
這個例子是Users\wuhuhuan\Desktop路徑下有個資料夾 lxh 。在windows 系統dos 裡面執行的命令是 winrar a 要將檔案儲存的名稱(可以帶路徑) 要壓縮的路徑 -r
具體看程式碼註釋。本人剛剛接觸python 請多多指教。