1.最近下了一堆文件,但是都是分文件夹存的。例:
想手动移动到一起实在太麻烦了,于是写了个脚本,顺便百度了一份其他大佬的MD5去重
思路:
1.遍历当前及下层文件夹获取文件,写入到另一文件夹,如果重名则移动时更名。
2.完成后进行去重
# -*- coding:utf-8 -*-
import os
import shutil
import hashlib
import datetime
#移动文件到指定文件夹
def movefile(rootdir,des_path):
#获取目录下文件名清单
list=os.listdir(rootdir)
for i in range(0,len(list)): #遍历目录下的所有文件夹
path=os.path.join(rootdir,list[i])
if os.path.isdir(path): # 判断是否为文件夹
for item in os.listdir(path): # 遍历该文件夹中的所有文件
if os.path.isdir(item): # 跳过第三层文件夹
print("跳过多级目录")
continue
dirname=os.path.join(rootdir,list[i]) # 将根目录与文件夹名连接起来,获取文件目录
full_path=os.path.join(dirname,item) # 将文件目录与文件名连接起来,形成原来完整路径
print(full_path)
# 如果有重名文件,就加上一个数字
if os.path.exists(os.path.join(des_path, item)):
print("文件已存在,重命名")
for j in range(1, 100):
if not os.path.exists(os.path.join(des_path,str(j) + item)):
rename = str(j) + item
break
ren_path = os.path.join(des_path,rename)
shutil.move(full_path,ren_path) # 移动文件到目标路径并更名
else:
shutil.move(full_path,des_path) # 移动文件到目标路径
print(full_path)
else:
print("不为文件夹,尝试直接拷贝")
print(path)
# 如果有重名文件,就加上一个数字 "/*.[jp][pn]g"
if os.path.exists(os.path.join(des_path, list[i])):
for j in range(1, 100):
if not os.path.exists(os.path.join(des_path,list[i] + str(j))):
rename = str(j)+list[i]
break
shutil.move(path,os.path.join(des_path,rename))
else:
shutil.move(path,des_path) # 移动文件到目标路径
# MD5去重
def getmd5(filename):
file_txt = open(filename, 'rb').read()
m = hashlib.md5(file_txt)
return m.hexdigest()
def MD5RemoveFile(filepath):
if os.path.isdir(filepath):
all_md5 = []
total_file = 0
total_delete = 0
for file in os.listdir(filepath):
total_file += 1
real_path = os.path.join(filepath, file)
if os.path.isfile(real_path) == True:
filemd5 = getmd5(real_path)
if filemd5 in all_md5:
total_delete += 1
os.remove(real_path)
else:
all_md5.append(filemd5)
print (u'文件总数:', total_file)
print (u'删除个数:', total_delete)
else:
print("检查目录不为文件夹")
if __name__ == '__main__':
start = datetime.datetime.now()
rootdir=input("请输入想移动文件的目录 注:为文件的上层目录")
des_path=input("请输入想移动到的目录")
if not os.path.exists(des_path):
print("移动目录不存在,自动创建")
os.makedirs(des_path)
if not os.path.exists(rootdir):
print("原始目录不存在")
else:
movefile(rootdir,des_path)
print("移动完成")
print("")
print("执行MD5查重")
MD5RemoveFile(des_path)
end = datetime.datetime.now()
time_last = end - start
print (u'耗时:', time_last, u'秒')
注:不检查第三层目录
标签:join,批量,python,des,文件夹,print,path,os,MD5
来源: https://www.cnblogs.com/holdv/p/14203450.html