python删除某一文件夹下的重复文件

2022-12-07,,,,


#2022-10-28
import hashlib
import os
import time def getmd5(filename):
"""
获取文件 md5 码
:param filename: 文件路径
:return: 文件 md5 码
"""
file_txt = open(filename, 'rb').read()
# 调用一个md5对象
m = hashlib.md5(file_txt)
# hexdigest()方法来获取摘要(加密结果)
return m.hexdigest() def main():
# 文件夹路径
path = input("path: ")
# 存放文件的 md5 码
all_md5 = {} # 改为字典
total_file = 0
total_delete = 0
# 开始时间
start = time.time()
# 遍历文件夹下的所有文件
for file in os.listdir(path):
# 文件数量加 1
total_file += 1
# 文件的路径
real_path = os.path.join(path, file)
# 判断文件是否是文件
if os.path.isfile(real_path) == True:
# 获取文件的md5码
filemd5 = getmd5(real_path)
# 如果文件 md5 已存在,则删除此文件
if filemd5 in all_md5.keys(): # 字典的键为文件 md5 码
total_delete += 1
print('删除', file)
os.remove(real_path)
#os.remove(path +"\\" + file)
else:
# 如果文件 md5 不存在,则将此文件的 md5 码添加到 all_md5 字典中
all_md5[filemd5] = ""
# 结束时间
end = time.time()
time_last = end - start
print('文件总数:', total_file)
print('删除个数:', total_delete)
print('耗时:', time_last, '秒') if __name__ == '__main__':
main()

来源: http://t.csdn.cn/uLV2g

python删除某一文件夹下的重复文件的相关教程结束。

《python删除某一文件夹下的重复文件.doc》

下载本文的Word格式文档,以方便收藏与打印。