朔州網(wǎng)站建設(shè)四川seo哪里有
Python世界:文件自動化備份實(shí)踐
- 背景任務(wù)
- 實(shí)現(xiàn)思路
- 坑點(diǎn)小結(jié)
背景任務(wù)
問題來自《簡明Python教程》中的解決問題一章,提出實(shí)現(xiàn):對指定目錄做定期自動化備份。
最重要的改進(jìn)方向是不使用 os.system 方法來創(chuàng)建歸檔文件, 而是使用 zipfile 或 tarfile 內(nèi)置的模塊來創(chuàng)建它們的歸檔文件。 ——《簡明Python教程》
本文在其第4版示范代碼基礎(chǔ)上,嘗試采用內(nèi)部python自帶庫zipfile的方式,實(shí)現(xiàn)功能:進(jìn)行文件壓縮備份。
實(shí)現(xiàn)思路
文件命名demo_backup_v5.py
,視為改進(jìn)的第5版實(shí)現(xiàn),除采用自帶zipfile的方式,還有以下更新:
- 支持外部自定義設(shè)參
- 支持自定義壓縮文件內(nèi)目錄名稱,并去除冗余絕對路徑
編碼思路:
- 指定待備份目錄和目標(biāo)備份路徑
- 按日期建立文件夾
- 按時間建立壓縮文件
首先,進(jìn)行輸入前處理,對目錄路徑進(jìn)行處理:
if len(sys.argv) >= 3: # 有外部入?yún)?#xff0c;取外部輸入tobe_backup_dir = sys.argv[1] # input dir, sys.argv[0] the name of python filetarget_dir = sys.argv[2] # output dircomment_info = input("enter a comment information => ")else: # 無外部入?yún)?#xff0c;則內(nèi)部設(shè)定# tobe_backup_dir = "C:\\Users\\other"tobe_backup_dir = r"E:\roma_data\code_data_in\inbox"target_dir = "E:\\roma_data\\code_test"comment_info = "test demo"
其次,正式進(jìn)入程序處理函數(shù):backup_proc()
,先判斷目標(biāo)備份目錄是否存在,如不存在,先構(gòu)造1個。
接著,按日期today進(jìn)行備份文件夾創(chuàng)建,按時間now進(jìn)行壓縮文件命名備份。
最后,遍歷待備份源目錄所有文件,將其壓縮為時間now命名的zip文件中。
# 僅支持單個目錄備份
def backup_proc(tobe_backup_dir, target_dir, comment_info):if_not_exist_then_mkdir(target_dir)today = target_dir + os.sep + "backup_" + time.strftime("%Y%m%d") # 年、月、日now = time.strftime("%H%M%S") # 小時、分鐘、秒print("Successfully created")# zip命名及目錄處理prefix = today + os.sep + nowif len(comment_info) == 0:target = prefix + '.zip'else:target = prefix + "_" + comment_info.replace(" ", "_") + '.zip'if_not_exist_then_mkdir(today)# 參考鏈接:https://blog.csdn.net/csrh131/article/details/107895772# zipfile打開文件句柄, with打開不用手動關(guān)閉with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as f:for root_dir, dir_list, file_list in os.walk(tobe_backup_dir): # 能遍歷子目錄所有文件for name in file_list:target_file = os.path.join(root_dir, name)all_file_direct_zip = Falseif all_file_direct_zip: # 不加內(nèi)部目錄zip_internal_dir_prefix = os.sepelse: # 加內(nèi)部目錄zip_internal_dir_prefix = comment_info + os.sep# 去掉絕對路徑指定壓縮包里面的文件所在目錄結(jié)構(gòu) arcname = zip_internal_dir_prefix + target_file.replace(tobe_backup_dir, "")# arcname = target_file.replace(tobe_backup_dir, "")f.write(target_file, arcname=arcname)return
測試用例
- python外部入?yún)?
- python demo_backup_v5.py “E:\roma_data\code_data_in\inbox” “E:\roma_data\code_test”
- python內(nèi)部入?yún)?
- python demo_backup_v5.py
本實(shí)現(xiàn)的一個缺點(diǎn)是,僅支持單一目錄備份,秉持短小精悍原則,如需多目錄備份可在以上做加法。
坑點(diǎn)小結(jié)
坑點(diǎn)1:不要多級目錄,去除絕對路徑
解決:zipfile壓縮包如何避免絕對路徑
坑點(diǎn)2:Unable to find python module
運(yùn)行if not os.path.exists(path_in)報(bào)錯。
根因:python有多個版本,3.6運(yùn)行時不支持,需要>=3.8。
解決:Ctrl + Shift + P,輸入Select Interpreter,指定高版本版本解釋器。
參考:link1,link2
坑點(diǎn)3:TypeError: stat: path should be string, bytes, os.PathLike or integer, not list
根因:輸入的path路徑是個list沒有拆解開,索引訪問元素給string輸入。
示例實(shí)現(xiàn):
# -*- coding: utf-8 -*-
"""
Created on 09/03/24
功能:文件備份
1、指定待備份目錄和目標(biāo)備份路徑
2、按日期建立文件夾
3、按時間建立壓縮文件
"""import os
import time
import sys
import zipfile# 判斷該目錄是否存在,如不存在,則創(chuàng)建
def if_not_exist_then_mkdir(path_in):if not os.path.exists(path_in):os.mkdir(path_in)print("Successfully created directory", path_in)# 僅支持單個目錄備份
def backup_proc(tobe_backup_dir, target_dir, comment_info):if_not_exist_then_mkdir(target_dir)today = target_dir + os.sep + "backup_" + time.strftime("%Y%m%d") # 年、月、日now = time.strftime("%H%M%S") # 小時、分鐘、秒print("Successfully created")# zip命名及目錄處理prefix = today + os.sep + nowif len(comment_info) == 0:target = prefix + '.zip'else:target = prefix + "_" + comment_info.replace(" ", "_") + '.zip'if_not_exist_then_mkdir(today)# 參考鏈接:https://blog.csdn.net/csrh131/article/details/107895772# zipfile打開文件句柄, with打開不用手動關(guān)閉with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as f:for root_dir, dir_list, file_list in os.walk(tobe_backup_dir): # 能遍歷子目錄所有文件for name in file_list:target_file = os.path.join(root_dir, name)all_file_direct_zip = Falseif all_file_direct_zip: # 不加內(nèi)部目錄zip_internal_dir_prefix = os.sepelse: # 加內(nèi)部目錄zip_internal_dir_prefix = comment_info + os.sep# 去掉絕對路徑指定壓縮包里面的文件所在目錄結(jié)構(gòu) arcname = zip_internal_dir_prefix + target_file.replace(tobe_backup_dir, "")# arcname = target_file.replace(tobe_backup_dir, "")f.write(target_file, arcname=arcname)returnif __name__ == '__main__':print('start!')# 前處理if len(sys.argv) >= 3: # 有外部入?yún)?#xff0c;取外部輸入tobe_backup_dir = sys.argv[1] # input dir, sys.argv[0] the name of python filetarget_dir = sys.argv[2] # output dircomment_info = input("enter a comment information => ")else: # 無外部入?yún)?#xff0c;則內(nèi)部設(shè)定# tobe_backup_dir = "C:\\Users\\other"tobe_backup_dir = r"E:\roma_data\code_data_in\inbox"target_dir = "E:\\roma_data\\code_test"comment_info = "test demo"# 正式運(yùn)行backup_proc(tobe_backup_dir, target_dir, comment_info)# 正式退出main函數(shù)進(jìn)程,以免main函數(shù)空跑print('done!')sys.exit()