1. 程式人生 > >Python3_自動化練習題_md5值對檔名進行重新命名

Python3_自動化練習題_md5值對檔名進行重新命名

1:獲取當前目錄下所有檔案,然後做如下處理:

1)檔名去重複。
2)選出檔案大於10m的
3)獲取到檔案的md5值,然後利用這個md5值對檔名進行重新命名(其中md5代表一個檔案屬性)
4)打印出最後的符合條件的所有檔名

溫馨提示:
1)我們是要獲取所有的檔案 而不是目錄
2)去重複不是刪除檔案,而是對重複的檔名進行重新命名
3)想辦法獲取檔案的md5值
4)最好是函式的形式實現哦

 1 import os
 2 import hashlib
 3 
 4 allfiles = []
 5 tempdict = {}
 6 end_file = []
 7 
 8 
 9 class GetFlie:
10 def __init__(self, dirpath): 11 self.dirpath = dirpath 12 13 def get_all_file(self, ): 14 # 通過os.walk獲取目錄下的所有檔名 15 for root, dirs, files in os.walk(self.dirpath): 16 for file in files: 17 # 判斷size 18 size = os.path.getsize(os.path.join(root, file))
19 if size <= 10485760: 20 # 檔名新增到allfiles列表裡 21 allfiles.append(os.path.join(root, file)) 22 # 重新命名 23 for i in range(len(allfiles)): 24 # 如果md5在字典的key已存在 25 if self.get_md5(allfiles[i]) in tempdict.keys():
26 tempdict[self.get_md5(allfiles[i]) + str(i)] = allfiles[i].split(".")[0] + str(i) + "." + allfiles[i].split(".")[-1] 27 else: 28 tempdict[self.get_md5(allfiles[i])] = allfiles[i] 29 # 最後的檔案 30 for file in tempdict.values(): 31 end_file.append(file) 32 33 return end_file 34 35 @staticmethod 36 def get_md5(filename): 37 f = open(filename, 'rb') 38 m1 = hashlib.md5() # 獲取一個md5加密演算法物件 39 m1.update(f.read()) # 讀取檔案,制定需要加密的字串 40 hash_code = m1.hexdigest() # 獲取加密後的16進位制字串 41 f.close() 42 md5 = str(hash_code).lower() 43 return md5 44 45 46 if __name__ == '__main__': 47 path = r'I:\lesson_practice\tool' 48 print(GetFlie(path).get_all_file())