frank1126lin

由于自己的手机经常备份,备份后原来的图片视频没有删除,下次再备份的时候移动硬盘上又多了很多重复图片,于是想着能不能用提取MD5校验码的方式识别出重复的文件,然后处理下硬盘里已经重复的内容.

考虑到最近在学python,于是通过上网查资料和内容,借很多大牛的轮子来试了一下,搞了两个晚上,终于算是阶段性完成,能达到目标的方法.主要难点有三个:

  1. 获取文件的MD5码;
  2. 不能更改文件的后缀名(例如原来是jpg的保留jpg,MP4的保留MP4);
  3. 遍历目标文件夹内所有文件;

不多说了,上代码,各位如有适合请拿去不谢.如有帮助,请记得留言,谢谢.

 1 # !/usr/bin/env python37
 2 # -*- coding: utf-8 -*-
 3 # @File  : renamefile.py
 4 # @Author: Frank
 5 # @Date  : 2018-09-22
 6 
 7 import hashlib
 8 import os
 9 import time
10 
11 # 1.获取文件MD5值
12 def get_md5(file_name,path):
13     with open(os.path.join(path,file_name),\'rb\') as f:
14         md5obj = hashlib.md5()
15         md5obj.update(f.read())
16         hash = md5obj.hexdigest()
17     #print(hash,type(hash))
18     return hash
19 
20 #2.找出当前的文件的后缀名
21 def file_type(file):
22     filename = file.split(\'.\')[0]
23     filetype = file.split(\'.\')[-1]
24     #print(filename,filetype)
25     return filetype
26 
27 
28 #3.主函数:查找目标目录下的所有文件,并使用MD5值及后缀名重命名当前文件
29 def main(path):
30     winerror = []
31     for root,dirlist,filelist in os.walk(path):
32         for file in filelist:
33             newname =  \'{0}.{1}\'.format(get_md5(file,path), file_type(file))
34             print(newname)
35             try:
36                 if os.path.join(path,newname) == os.path.join(path,file):
37                     pass
38                 else:
39                     print(\'Now Renaming:\', file, \'To\', newname)
40                     os.rename(os.path.join(path,file),os.path.join(path,newname))
41             except WindowsError:
42                 nickname = \'{0}.{1}\'.format(str(len(winerror)),file_type(file))
43                 print(\'WindowsError for:\',file, \'Renaming to:\', nickname)
44                 winerror.append(file)
45                 os.rename(os.path.join(path,file),os.path.join(path,nickname))
46     print(winerror)
47     print(len(winerror))
48 
49 
50 
51 #4.执行
52 path = r\'D:\iPhoneshowdup\nameduplicate\'
53 if __name__ == \'__main__\':
54     starttime = time.time()
55     main(path)
56     endtime = time.time()
57     usetime = endtime - starttime
58     print(\'总计用时:\', usetime, \'s\')

 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-26
  • 2022-01-01
  • 2021-09-26
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-07
  • 2022-12-23
  • 2021-06-17
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案