工作中偶爾會(huì)遇到文件去重的事情,收到一大堆文件,名稱各不相同,分析文件的時(shí)候發(fā)現(xiàn)有不少重復(fù)的文件,導(dǎo)致工作效率低下,那么,這里就寫(xiě)了一個(gè)python腳本實(shí)現(xiàn)文件去重功能
import os
import shutil
import hashlib
# 對(duì)文件去重
# 計(jì)算每個(gè)文件的md5值,據(jù)此進(jìn)行去重
def only_one(test_path):
md5_list = []
count = 0
for current_folder, list_folders, files in os.walk(test_path):
for file in files:
file_path = current_folder + '\\' + file # 獲取每個(gè)文件的路徑
f = open(file_path, 'rb') # 開(kāi)始計(jì)算每個(gè)文件的md5值
md5obj = hashlib.md5()
md5obj.update(f.read())
get_hash = md5obj.hexdigest()
f.close()
md5_value = str(get_hash).upper()
# 開(kāi)始去重
if md5_value in md5_list: # 如果這個(gè)文件的md5值曾經(jīng)出現(xiàn)過(guò),就不對(duì)它做任何處理
count += 1
print('\033[31m[-] 發(fā)現(xiàn)重復(fù)文件:\033[0m' + str(file))
else:
md5_list.append(md5_value) # 如果這個(gè)文件的md5值不存在列表中,就添加進(jìn)列表中
shutil.copy(file_path, path1)
print('\033[31m[-] 共發(fā)現(xiàn)重復(fù)文件:{}個(gè)\033[0m'.format(count))
if __name__ == '__main__':
print('\033[4;33m[+] 此腳本會(huì)檢查指定路徑下的所有文件,通過(guò)計(jì)算文件的MD5值進(jìn)行去重\033[0m')
print('\033[4;33m[+] 去重后的文件會(huì)復(fù)制到桌面新文件夾中,源文件不會(huì)丟失\033[0m')
path = input('\033[34m[+] 請(qǐng)輸入文件夾地址:\033[0m')
os.chdir(path)
# path1 用來(lái)存放所有的去重結(jié)果
desktop_path = os.path.join(os.path.expanduser("~"), 'Desktop') # 獲取桌面路徑
path1 = os.path.join(desktop_path, '去重結(jié)果')
os.makedirs(path1)
only_one(path)
print('\033[32m[-] 現(xiàn)有非重復(fù)文件共計(jì):{}個(gè)\033[0m'.format(len(os.listdir(path1))))
到此這篇關(guān)于python實(shí)現(xiàn)MD5進(jìn)行文件去重的示例代碼的文章就介紹到這了,更多相關(guān)python MD5文件去重內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!