zoukankan      html  css  js  c++  java
  • Python3_自动化练习题_md5值对文件名进行重命名

    1:获取当前目录下所有文件,然后做如下处理:

    1)文件名去重复。
    2)选出文件大于10m的
    3)获取到文件的md5值,然后利用这个md5值对文件名进行重命名(其中md5代表一个文件属性)
    4)打印出最后的符合条件的所有文件名

    温馨提示:
    1)我们是要获取所有的文件 而不是目录
    2)去重复不是删除文件,而是对重复的文件名进行重命名
    3)想办法获取文件的md5值
    4)最好是函数的形式实现哦

     1 import os
     2 import hashlib
     3 
     4 allfiles = []
     5 tempdict = {}
     6 end_file = []
     7 
     8 
     9 class GetFlie:
    10     def __init__(self, dirpath):
    11         self.dirpath = dirpath
    12 
    13     def get_all_file(self, ):
    14         # 通过os.walk获取目录下的所有文件名
    15         for root, dirs, files in os.walk(self.dirpath):
    16             for file in files:
    17                 # 判断size
    18                 size = os.path.getsize(os.path.join(root, file))
    19                 if size <= 10485760:
    20                     # 文件名添加到allfiles列表里
    21                     allfiles.append(os.path.join(root, file))
    22         # 重命名
    23         for i in range(len(allfiles)):
    24             # 如果md5在字典的key已存在
    25             if self.get_md5(allfiles[i]) in tempdict.keys():
    26                 tempdict[self.get_md5(allfiles[i]) + str(i)] = allfiles[i].split(".")[0] + str(i) + "." + allfiles[i].split(".")[-1]
    27             else:
    28                 tempdict[self.get_md5(allfiles[i])] = allfiles[i]
    29         # 最后的文件
    30         for file in tempdict.values():
    31             end_file.append(file)
    32 
    33         return end_file
    34 
    35     @staticmethod
    36     def get_md5(filename):
    37         f = open(filename, 'rb')
    38         m1 = hashlib.md5()  # 获取一个md5加密算法对象
    39         m1.update(f.read())  # 读取文件,制定需要加密的字符串
    40         hash_code = m1.hexdigest()  # 获取加密后的16进制字符串
    41         f.close()
    42         md5 = str(hash_code).lower()
    43         return md5
    44 
    45 
    46 if __name__ == '__main__':
    47     path = r'I:lesson_practice	ool'
    48     print(GetFlie(path).get_all_file())
  • 相关阅读:
    Swift的闭包(一):闭包简介、闭包表达式的优化
    iOS 用户体验之音频
    【iOS】Core Bluetooth
    【iOS】3D Touch
    golang中channel的超时处理
    Objective-C 中的 BOOL
    2015年总结
    load vs. initialize
    正则表达式
    When does layoutSubviews get called?
  • 原文地址:https://www.cnblogs.com/monica711/p/10076450.html
Copyright © 2011-2022 走看看