20181205Python 自动化笔试题,挑战你的知识库

本贴最后更新于 1492 天前,其中的信息可能已经时移俗易

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

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

温馨提示:

  1. 我们是要获取所有的文件 而不是目录
  2. 去重复不是删除文件,而是对重复的文件名进行重命名
  3. 想办法获取文件的md5值
  4. 最好是函数的形式实现哦
1 操作
huahua 在 2020-08-07 21:52:58 更新了该帖
18 回帖
请输入回帖内容 ...
  • huahua

    😎 各位请出招吧!!!最后请做出题目的宝宝,贴代码上来!注意Markdown的语法哟!!!

  • 其他回帖
  • emma
    import os
    import hashlib
    def get_md5(file_path):#计算md5值
        with open(file_path, 'rb') as f:
            md5 = hashlib.md5()
            while True:
                b=f.read(8096)#分段读取
                if not b:
                    break   #如果读取结束了就跳出循环
                md5.update(b)
            hash = md5.hexdigest()
        return hash   #返回文件的md5值
    
    file_list = []
    new_file=[]
    name=[]
    def find_file(path): #获取所有的文件,并筛选出大于10M的文件
        if os.path.isdir(path)==True:
            for items in os.listdir(path):
                new_path=os.path.join(path,items)
                find_file(new_path)
        else:
            if os.path.getsize(path) >=10*1024*1024:
                file_list.append(path)
        return file_list
    
    
    
    def find_name(file): #找到重名的文件并修改
        new_path=[]
        name=[]
        for items in file:
            name.append(os.path.split(items))
        for i in range(len(name)-1):
            for j in range(i+1,len(name)):
                if name[i][-1]==name[j][-1]:
                    new_path.append(os.path.join(name[i][0],name[i][-1]))
                    new_path.append(os.path.join(name[j][0],name[j][-1]))
        for items in new_path: #new_path里面是所有重名的文件路径集合
            md5=get_md5(items)
            file=os.path.split(items)[-1]#获取文件名
            newname=md5+'.'+file.split('.')[-1]#拼接新文件名
            os.rename(items,os.path.join(os.path.split(items)[0],newname)) #重命名
    
    path=os.getcwd()
    print(path)
    file=find_file(path)
    find_name(file)
    
  • zjj
    
    # -*- coding:utf-8 -*-
    
    import os
    import hashlib
    
    FILE_LIST = [] #所有文件列表
    
    #获取目录下所有文件
    def  get_file_list(dir_path):
        global FILE_LIST
        dir_list = {}
        if not os.path.isdir(dir_path):
            print('目录不存在')
        else:
            dir_list = os.listdir(dir_path)
            for file in dir_list:
                file_path = dir_path + '\\' +file
                if os.path.isdir(file_path):
                    get_file_list(file_path) #目录包含目录需读得里面的文件
                else:
                    FILE_LIST.append(file_path)
        #print(FILE_LIST)
    
    #获取文件的md5的值
    def get_file_md5(file_path):
        def read_chunks(fh):
            fh.seek(0)
            chunks = fh.read(8096)  #文件过大一块块读
            while chunks:
                yield chunks
                chunks = fh.read(8096)
            else: #最后将游标放回到文件头
                fh.seek(0)
    
        myhash = hashlib.md5()
        with open(file_path,'rb') as fh:
            for chunk in read_chunks(fh):
                myhash.update(chunk)
    
        return myhash.hexdigest()
    
    
    #文件大小过滤及重命名
    def file_operator(dir_path,size,file_size_unit):
        count = 0
        file_dict = {}
        get_file_list(dir_path) #获取目录下所有文件
    
        for file in FILE_LIST:
            file_size = os.path.getsize(file)
            if file_size_unit == 'Byte':
                file_size = file_size
            elif file_size_unit == 'KB':
                file_size = file_size / 1024
            elif file_size_unit == 'M':
                file_size = file_size / 1024 / 1024
            elif file_size_unit == 'G':
                file_size = file_size / 1024 / 1024 / 1024
            else:
                print('文件单位默认为M处理')
                ile_size = file_size / 1024 / 1024
    
            file_size = round(file_size,2)
            file_md5 = get_file_md5(file)   #获取文件的md5码
            file_path = os.path.split(file)
            file_full_name = file_path[1]  #获取文件的名称,不包含目录
            count += 1
            file_type = file_full_name[file_full_name.index('.'):] #获取文件的类型
            #新目录名 = 目录+文件+文件md5码+记数+文件类型
            new_name = file_path[0] + '\\' + str(file_md5) + '_' + str(count) + file_type
            os.rename(file,new_name)
            if(file_size > size): #过滤文件大小不足的
                file_dict[new_name] = str(file_size) + file_size_unit
    
        print('大小超过{0}{1}的文件列表为:\n{2}'.format(size,file_size_unit,file_dict))
    
    if __name__ == '__main__':
        file_operator(r'G:\test',10,'M')
    
  • D_Sai
    import os
    import hashlib
    
    class MyFile:
        '''文件夹类'''
    
        def __init__(self, myPath):
            self.rootPath = myPath
    
        def del_files(self):
            '''遍历文件夹'''
            for root, dirs, files in os.walk(self.rootPath):#逐层遍历文件夹
                for file in files:#遍历每一个文件
                    File1.append(os.path.join(root, file))#每一个文件放在总的列表下
                    fileSize = os.path.getsize(os.path.join(root, file))
                    if fileSize >= 10*1024*1024:
                        File2.append(os.path.join(root, file))
            #文件名去重
            for item in File1:
                if item not in File3:
                    md = self.get_file_md5(item)
                    File3.append(item)
                else:
                    self.get_file_md5(item)
                    File4.append(md)
    
        def get_file_md5(slef, filename):
            '''得到每个文件的md5'''
            md5 = None
            if os.path.isfile(filename):
                f = open(filename, "rb")
                fileMd5 = hashlib.md5()
                fileMd5.update(f.read())
                hashCode = fileMd5.hexdigest()
                f.close()
                md5 = str(hashCode).lower()
                return md5
            else:
                print("这不是一个文件,请重新确认路径。")
                return
    
    
    if __name__ == '__main__':
        File1 = []  # 获取所有带路径文件名
        File2 = []  # 获取大于10M的带路径文件名
        File3 = []  # 获取去重后的带路径文件名
        File4 = []  # 存放重复名字md5
        myFile = MyFile(r'C:\Users\admin\Desktop\柠檬班书籍')
        myFile.del_files()
        print("File1:", File1)
        print("File2", File2)
        print("File3", File3)
        print("File4", File4)
    
  • 查看更多回帖