zoukankan      html  css  js  c++  java
  • python之读取文件的MD5码并重命名文件

    由于自己的手机经常备份,备份后原来的图片视频没有删除,下次再备份的时候移动硬盘上又多了很多重复图片,于是想着能不能用提取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
    ameduplicate'
    53 if __name__ == '__main__':
    54     starttime = time.time()
    55     main(path)
    56     endtime = time.time()
    57     usetime = endtime - starttime
    58     print('总计用时:', usetime, 's')
  • 相关阅读:
    Codeforces 691A Fashion in Berland
    HDU 5741 Helter Skelter
    HDU 5735 Born Slippy
    HDU 5739 Fantasia
    HDU 5738 Eureka
    HDU 5734 Acperience
    HDU 5742 It's All In The Mind
    POJ Euro Efficiency 1252
    AtCoder Beginner Contest 067 C
    AtCoder Beginner Contest 067 D
  • 原文地址:https://www.cnblogs.com/frank1126lin/p/9694239.html
Copyright © 2011-2022 走看看