非常簡(jiǎn)單的程序,只是考慮的比較多缴啡,寫的比較多=-=
設(shè)計(jì)思路
灰常簡(jiǎn)單
- 遞歸搜索目錄中的所有文件壁晒。
- 計(jì)算這些文件的MD5并存儲(chǔ)在“Dict”中。
- 如果“Dict”有此MD5值业栅,則將文件移動(dòng)到默認(rèn)文件夾(“./ Duplicates”)并重命名秒咐。
考慮到的小細(xì)節(jié)
- 大文件以塊的形式讀取。
- 重復(fù)文件移動(dòng)名稱較長(zhǎng)的文件碘裕。
- 重命名時(shí)携取,在原來的名稱中添加一個(gè)數(shù)字。
- 不要更改后綴名(如果有)
The end =-=
代碼
程序和說明已經(jīng)公布在github
https://github.com/atlasbioinfo/SearchDuplicateFiles
from os import walk,path,mkdir
from hashlib import md5
from shutil import copy,move
def getMd5(fname):
m = md5()
with open(fname,'rb') as fobj:
while True:
data = fobj.read(4096)
if not data:
break
m.update(data)
return m.hexdigest()
if __name__ == '__main__':
#默認(rèn)把重復(fù)文件移動(dòng)到這個(gè)文件夾帮孔,可以自定義名字
#Default to move the duplicate file to this folder and can customize the name
dupDir="Duplications"
mkdir(dupDir)
mdFile={}
fileName={}
for fpath,dirs,fs in walk('.'):
for f in fs:
tfile=path.join(fpath,f)
if (path.samefile(fpath,dupDir)):
continue
tMD=getMd5(tfile)
if (tMD in mdFile):
mdFile[tMD]+=1
if (len(f)>len(path.basename(fileName[tMD]))):
move(tfile,path.join(dupDir,path.splitext(f)[0]+str(mdFile[tMD])+path.splitext(f)[1]))
else:
tname=path.basename(fileName[tMD])
move(fileName[tMD],path.join(dupDir,path.splitext(tname)[0]+str(mdFile[tMD])+path.splitext(tname)[1]))
fileName[tMD]=tfile
else:
mdFile[tMD]=1
fileName[tMD]=tfile
舉個(gè)例子Example
ORI:
temp.py
temp_copy.py
temp_2.py
After deduplicate......
Retain:
temp.py
Moved:
temp_copy2.py
temp_23.py