本文實例講述了python實現的刪除重復文件或圖片功能。分享給大家供大家參考,具體如下:
通過python爬蟲或其他方式保存的圖片文件通常包含一些重復的圖片或文件,
通過下面的python代碼可以將重復的文件刪除以達到去重的目的。其中,文件目錄結構如下圖:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
# /usr/bin/env python # -*- coding:utf-8 -*- # 運行的代碼文件要放到刪除重復的文件或圖片所包含的目錄中 import os import hashlib def filecount(): filecount = int (os.popen( 'dir /b |find /v /c ""' ).read()) return (filecount) def md5sum(filename): f = open (filename, 'rb' ) md5 = hashlib.md5() while true: fb = f.read( 8096 ) if not fb: break md5.update(fb) f.close() return (md5.hexdigest()) def delfile(): all_md5 = {} filedir = os.walk(os.getcwd()) for i in filedir: for tlie in i[ 2 ]: if md5sum(tlie) in all_md5.values(): os.remove(tlie) else : all_md5[tlie] = md5sum(tlie) if __name__ = = '__main__' : oldf = filecount() print ( '去重前有' , oldf, '個文件\n\n\n請稍等正在刪除重復文件...' ) delfile() print ( '\n\n去重后剩' , filecount(), '個文件' ) print ( '\n\n一共刪除了' , oldf - filecount(), '個文件\n\n' ) |
希望本文所述對大家python程序設計有所幫助。
原文鏈接:https://blog.csdn.net/loveliuzz/article/details/81661281