'''
找出文件夹中的相同文件,并移动到指定文件夹中
'''
import hashlib
import os,shutil
def md5_vaule(dir):
hasher = hashlib.md5()
afile = open(dir, 'rb')
buf = afile.read()
a = hasher.update(buf)
return str(hasher.hexdigest())
def file_name(file_dir):
all =[]
for root, dirs, files in os.walk(file_dir):
tmp = []
# print('root_dir:', root) # 当前目录路径
# print('sub_dirs:', dirs) # 当前路径下所有子目录
# print('files:', files) # 当前路径下所有非目录子文件
for i in files:
tmp.append(root+"\\"+i)
for j in tmp:
all.append(j)
return all
def need_del(all_md5_in):
all_md5_no_repeat = list(set(all_md5_in))
all_md5_no_repeat.sort(key=all_md5_in.index)
need_del_index = []
for temp in all_md5_no_repeat:
flag = 0
list_index = []
for n in range(all_md5_in.count(temp)):
sec = flag
flag = all_md5_in[flag:].index(temp)
list_index.append(flag + sec)
flag = list_index[-1:][0] + 1
for k in range(1, len(list_index)):
need_del_index.append(list_index[k])
return need_del_index
def move_file(orgfile, newpath):
shutil.move(orgfile, newpath)
def new_folder_create(in_del_folder, in_origl_folder): # 将重复文件移动到指定文件夹,为防止出现文件名相同情况,后面会补上文件原所在路径
tmp1 = in_origl_folder.split(".")
tmp2 = tmp1[-2].split(":")
res_path = in_del_folder + tmp2[-1]
os.makedirs(res_path)
return res_path
def all_file_and_md5(filename, filemd5): # 显示所有文件及其对应的md5
for i in range(len(filename)):
res=filename[i]+" "+filemd5[i]
print(res)
def how_much_repeat(all_in): # 找出有多少相同的文件
all_md5_set = list(set(all_in))
all_md5_set.sort(key = all_in.index)
# for k in all_md5_set:
# print(k)
return len(all_in)-len(all_md5_set)
if __name__ == '__main__':
file_names = file_name("D:\\重复") # 要处理的文件夹路径
del_folder = "D:\\重复del" # 将重复的文件拷到此路径下,为防止出现文件名相同情况,后面会补上文件原所在路径
all_md5 = []
file_names_beifen = []
all_md5_beifen = []
for i in file_names:
all_md5.append(md5_vaule(i))
file_names_beifen.append(i)
all_md5_beifen.append(md5_vaule(i))
# all_file_and_md5(file_names,all_md5) # 显示所有文件及其对应的md5
print("有多少重复 ", how_much_repeat(all_md5)) # 找出有多少相同的文件
need_del_file = need_del(all_md5) # 找出需要删除的文件在原文件夹数组中的位置(下标)
print("重复文件如下:")
for j in need_del_file: # 将重复的文件移动到指定文件夹中
print(file_names[j])
new_folder = new_folder_create(del_folder, file_names[j])
move_file(file_names[j], new_folder)
找出文件夹中的相同文件,并移动到指定文件夹中
最新推荐文章于 2024-01-04 13:52:50 发布