1. 程式人生 > 實用技巧 >python備份檔案(簡易)

python備份檔案(簡易)

步驟邏輯

要備份的資料夾:source = ["/opt/containerd"]

儲存備份資訊的資料夾 targz_dir = "/home/backup"

資料夾名(以當天日期為) day_dir = targz_dir +time.strftime('%Y%m%d')

檔名(當時時間為) filename = time.strftime('%H%M%S')

檢查資料夾是否存在 os.path.exist(day_dir)

資料夾路徑 需要壓縮 zip_dir = day_dir + os.sep +filename +'.zip' # os.sep 相容Windows平臺斜槓 os.sep = '\\'

檔案壓縮命令 command_shell = "zip -qr" +"zip_dir" + ' '.jion(source)

程式碼實現

source = ["/home/yjc/linux"]
targz_dir = "hoem/backup"
day_dir = targz_dir +time.strftime('%Y%m%d')
filename = time.strftime('%H%M%S')
zip_dir = day_dir +os.sep + filename +'.zip'
command_shell= "zip -qr" + zip_dir + ''+' '.join(source) 

if not os.path.exists(day_dir): # 判斷備份目錄是否存在,如果不存在則建立 os.mkdir(day_dir) if os.system(command_shell) == 0: print("備份成功") else: print("備份失敗")

簡易圖形介面

def bakcup():
    global entry_source
    global entry_tagz_dir
    source= entry_source.get()
    targz_dir=entry_tagz_dir.get()
    day_dir 
= targz_dir +time.strftime('%Y%m%d') filename = time.strftime('%H%M%S') zip_dir = day_dir +os.sep + filename +'.zip' command_shell= "zip -qr" + zip_dir + ''+' '.join(source) if not os.path.exists(day_dir): # 判斷備份目錄是否存在,如果不存在則建立 os.mkdir(day_dir) if os.system(command_shell) == 0: print("備份成功") else: print("備份失敗") #編寫介面佈局 root = tkinter.Tk() root.title('Backup') root.geometry("2000x2000") #第一行的兩個控制元件 dir_source = tkinter.Label(root,text='Source') dir_source.grid(row=0,column=0) entry_source = tkinter.Entry(root) entry_source.grid(row=0,column=1) # 第二行控制元件 target_dir = tkinter.Label(root,text='Target') target_dir.grid(row=1,column=0) entry_tagz_dir=tkinter.Entry(root) entry_tagz_dir.grid(row=1,column=1) #第三行控制元件 bak=tkinter.Button(root,text='Backup') bak.grid(row=3,column=0) bak["command"] = bakcup #介面開始 root.mainloop()