刪庫跑路?在我這裡永遠不可能!我有自動備份檔案的程式!
該程式包含以下個檔案:
Sync.py:主程式
Sync1.ini:配置檔案
Logger1.py:記錄器支援的模組
Sync.log是sync.py建立的檔案。
現在讓我們瞭解sync.py的程式碼,看看它是如何工作的。
1.匯入要使用的基本庫。
Import configparser.
Import time.
Import shutil.
Import hashlib.
From the distutils.dir_util import copy_tree.
From the collections, import OrderedDict.
Import the OS.
Import logger1 as log1.
以下程式碼為讀取Sync1.ini檔案:
def ConfRead():
config = configparser.ConfigParser()
config.read(“Sync1.ini”)
return (dict(config.items(“Para”)))
下面顯示的是從Sync.ini檔案中獲得的一些變數:
All_Config = ConfRead()
Freq = int(All_Config.get(“freq”))*60
Total_time = int(All_Config.get(“total_time”))*60
repeat = int(Total_time/Freq)
圖1:使用pyinstaller建立一個exe檔案
圖2:將exe檔案放在Windows資料夾中
以下函式md5用於計算檔案的雜湊值。如果修改檔案,則名稱保持不變,但雜湊值會更改。
def md5(fname,size=4096):
hash_md5 = hashlib.md5()
with open(fname, “rb”) as f:
for chunk in iter(lambda: f.read(size), b””):
hash_md5.update(chunk)
return hash_md5.hexdigest()
以下函式使用中介複製整個目錄:
def CopyDir(from1, to):
copy_tree(from1, to)
以下函式只將一個檔案複製到目標位置:
def CopyFiles(file, path_to_copy):
shutil.copy(file,path_to_copy)
圖3:CMD預設路徑
圖4:同步命令
以下函式建立一個字典,其中包含帶有檔案雜湊的檔名。該函式獲取源位置並生成所有檔案的字典:
def OriginalFiles():
drive = All_Config.get(“from”)
Files_Dict = OrderedDict()
print (drive)
for root, dir, files in os.walk(drive, topdown=True):
for file in files:
file = file.lower()
file_path = root+’\’+file
try:
hash1 = md5(file_path,size=4096)
#modification_time = int(os.path.getmtime(file_path))
rel_path = file_path.strip(drive)
Files_Dict[(hash1,rel_path)]= file_path
except Exception as e :
log1.logger.error(‘Error Original files: {0}’.format(e))
return Files_Dict
以下的函式建立一個字典,其中包含帶有檔案雜湊的檔名。該函式獲取目標位置並獲取所有當前檔案並生成字典。如果根資料夾不存在,則呼叫CopyDir函式。
def Destination():
Files_Dict = OrderedDict()
from1 = All_Config.get(“from”)
to= All_Config.get(“to”)
dir1= from1.rsplit(“\”,1)[1]
drive = to+dir1
#print (drive)
try:
if os.path.isdir(drive):
for root, dir, files in os.walk(drive, topdown=True):
for file in files:
file = file.lower()
file_path = root+’\’+file
try:
hash1 = md5(file_path,size=4096)
#modification_time = int(os.path.getmtime(file_path))
rel_path = file_path.strip(drive)
Files_Dict[(hash1,rel_path)]= file_path
except Exception as e :
log1.logger.error(‘Error Destination foor loop: {0}’.format(e))
return Files_Dict
else :
CopyDir(from1,drive)
log1.logger.info(‘Full folder: {0} copied’.format(from1))
return None
except Exception as e :
log1.logger.error(‘Error Destination: {0}’.format(e))
以下函式定義如下邏輯:
- 如果已使用資料夾建立檔案。
- 如果檔案已被修改。
圖5:複製完整資料夾
圖6:修改檔案後
在這兩種情況下,下面的程式碼只是比較原始字典和目標字典。如果建立或修改了任何檔案,則直譯器將從源複製檔案並將其貼上到目標中。
def LogicCompare():
from1 = All_Config.get(“from”)
to= All_Config.get(“to”)
Dest_dict = Destination()
if Dest_dict:
Source_dict = OriginalFiles()
remaining_files = set(Source_dict.keys())- set(Dest_dict.keys())
remaining_files= [Source_dict.get(k) for k in remaining_files]
for file_path in remaining_files:
try:
log1.logger.info(‘File: {0}’.format(file_path))
dir, file = file_path.rsplit(“\”,1)
rel_dir = from1.rsplit(“\”,1)[1]
rel_dir1 = dir.replace(from1,””)
dest_dir = to+rel_dir+”\”+rel_dir1
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir)
CopyFiles(file_path, dest_dir)
except Exception as e:
log1.logger.error(‘Error LogicCompare: {0}’.format(e))
下面的程式碼使用迴圈來反覆執行程式碼:
i = 0
while True:
if i >= repeat:
break
LogicCompare()
time.sleep(Freq)
i = i +1
來看Sync1.ini的檔案內容:
[Para]
From = K: esting1
To = E:
Freq = 1
Total_time = 5
在上面的程式碼中:
From:指定源目錄並獲取testing1資料夾的備份。
To:指定備份的位置。
Freq:在指定多少分鐘後進行備份。
Total_time:執行Total_time分鐘的程式碼時長。
我們來看看logger1.py的程式碼:
import logging
logger = logging.getLogger(“Mohit”)
logger.setLevel(logging.INFO)
fh = logging.FileHandler(“Sync.log”)
formatter = logging.Formatter(‘%(asctime)s - %(levelname)s - %(message)s’)
fh.setFormatter(formatter)
logger.addHandler(fh)
上面的程式碼非常簡單,可以在INFO模式下使用。
如果你不想使用直譯器來執行程式碼,可以建立一個Windows exe檔案,這將作為命令。轉換它可以用pyinstaller,我已經安裝了那個模組。
圖1中的命令將您的程式碼轉換為exe檔案,執行它不需要Python直譯器。
圖7:建立新檔案後
圖8:筆驅動器存在時的輸出
如何執行該程式
進群:960410445
執行如圖1所示的命令後,檢查名為Sync的資料夾。在此資料夾中,檢查名為dist的資料夾,您將在其中獲取.exe檔案。現在複製此.exe檔案並將其貼上到C:/ Windows資料夾中,如圖2所示。
現在開啟命令提示符。檢查當前資料夾,如圖3所示。在我的PC中,預設提示路徑為c:/ user / Mohit。在您的PC中,它可能會有所不同。因此,複製Sync1.ini檔案並將其貼上到c:/ user / <your-name>資料夾中。
現在插上外接筆式驅動器。檢查筆式驅動器碟符,它在我的PC中是E.
根據您的PC配置,更改放置在C:/ user / <your-name>目錄中的Sync1.ini引數。
現在開啟命令提示符並鍵入命令,如圖4所示。
現在檢查你的驅動器,檢視sync.log,它是在資料夾c:/ user / <your-name>中被建立的。
有四種情況可能:
- 當驅動器中沒有整個資料夾時(圖5)。
- 修改現有檔案時(圖6)。
- 建立新檔案時(圖7)。
- 最後一種情況是當筆驅動器不存在時的負面測試案例(圖8)。