python查找指定具有相同内容文件的方法
作者:秋风秋雨 发布时间:2023-08-14 17:20:04
标签:python,查找,文件
本文实例讲述了python查找指定具有相同内容文件的方法。分享给大家供大家参考。具体如下:
python代码用于查找指定具有相同内容的文件,可以同时指定多个目录
调用方式:python doublesdetector.py c:\;d:\;e:\ > doubles.txt
# Hello, this script is written in Python - http://www.python.org
# doublesdetector.py 1.0p
import os, os.path, string, sys, sha
message = """
doublesdetector.py 1.0p
This script will search for files that are identical
(whatever their name/date/time).
Syntax : python %s <directories>
where <directories> is a directory or a list of directories
separated by a semicolon (;)
Examples : python %s c:\windows
python %s c:\;d:\;e:\ > doubles.txt
python %s c:\program files > doubles.txt
This script is public domain. Feel free to reuse and tweak it.
The author of this script Sebastien SAUVAGE <sebsauvage at sebsauvage dot net>
http://sebsauvage.net/python/
""" % ((sys.argv[0], )*4)
def fileSHA ( filepath ) :
""" Compute SHA (Secure Hash Algorythm) of a file.
Input : filepath : full path and name of file (eg. 'c:\windows\emm386.exe')
Output : string : contains the hexadecimal representation of the SHA of the file.
returns '0' if file could not be read (file not found, no read rights...)
"""
try:
file = open(filepath,'rb')
digest = sha.new()
data = file.read(65536)
while len(data) != 0:
digest.update(data)
data = file.read(65536)
file.close()
except:
return '0'
else:
return digest.hexdigest()
def detectDoubles( directories ):
fileslist = {}
# Group all files by size (in the fileslist dictionnary)
for directory in directories.split(';'):
directory = os.path.abspath(directory)
sys.stderr.write('Scanning directory '+directory+'...')
os.path.walk(directory,callback,fileslist)
sys.stderr.write('\n')
sys.stderr.write('Comparing files...')
# Remove keys (filesize) in the dictionnary which have only 1 file
for (filesize,listoffiles) in fileslist.items():
if len(listoffiles) == 1:
del fileslist[filesize]
# Now compute SHA of files that have the same size,
# and group files by SHA (in the filessha dictionnary)
filessha = {}
while len(fileslist)>0:
(filesize,listoffiles) = fileslist.popitem()
for filepath in listoffiles:
sys.stderr.write('.')
sha = fileSHA(filepath)
if filessha.has_key(sha):
filessha[sha].append(filepath)
else:
filessha[sha] = [filepath]
if filessha.has_key('0'):
del filessha['0']
# Remove keys (sha) in the dictionnary which have only 1 file
for (sha,listoffiles) in filessha.items():
if len(listoffiles) == 1:
del filessha[sha]
sys.stderr.write('\n')
return filessha
def callback(fileslist,directory,files):
sys.stderr.write('.')
for fileName in files:
filepath = os.path.join(directory,fileName)
if os.path.isfile(filepath):
filesize = os.stat(filepath)[6]
if fileslist.has_key(filesize):
fileslist[filesize].append(filepath)
else:
fileslist[filesize] = [filepath]
if len(sys.argv)>1 :
doubles = detectDoubles(" ".join(sys.argv[1:]))
print 'The following files are identical:'
print '\n'.join(["----\n%s" % '\n'.join(doubles[filesha]) for filesha in doubles.keys()])
print '----'
else:
print message
希望本文所述对大家的Python程序设计有所帮助。


猜你喜欢
- 前言plt.contour是python中用于画等高线的函数,这里介绍一下plt.contour的使用。使用示例import numpy a
- FSO中除了可以对驱动器、文件夹的操作以外,功能最强大的就是对文件的操作了。它可以用来记数、内容管理、搜索还可生成动态HTML页面等等。一、
- 博主最近试在服务器上进行spark编程,因此,在开始编程作业之前,要先搭建一个便利的编程环境,这样才能做到舒心地开发。本文主要有以下内容:1
- 曲线一解释这里是使用matplotlib来绘制正态分布的曲线。代码实现import numpy as npimport matplotlib
- str='python String function'生成字符串变量str='python String func
- 首先新建一个dataframe:In[8]: df = pd.DataFrame({'name':list('ABC
- 一、说明 numpy.ufunc是什么函数?答
- import Exception# except 在捕获错误异常的时候 是要根据具体的错误类型来捕获的# 用一个块 可以捕获多个不同类型的异
- 目录项目引入flask-sqlalchemyORM简介及模型定义表关系类型及编码实现一对多关系(多对一关系)一对一关系多对多关系数据库基本操
- 说起INDEX SERVER,我自己本来用的也不多,不过前两天公司要做一个INDEX的搜索,我从网上找了好多的资料,仔细分析了以后自己启动了
- windows下mysql双向同步备份实现方法以下的文章主要讲述的是在windows环境下实现MySQL数据库的主从同步备份的正确操作方案,
- 问题jupyter notebook读入csv数据时出现错误“SyntaxError: (unicode error) ‘unicodees
- 目录一、外键约束什么是外键: 外键的使用条件:外键的定义语法:简单演示使用一、外键约束 &nbs
- 使用python中的pandas,xlrd,openpyxl库完成合并excel中指定sheet的操作# -*- coding: UTF-8
- 开发环境与配置win_x64Ubuntu14.04Python3.xpip安装pymysql模块直接使用pip安装 pip install
- 前情提要上文我们分析了挂载组件主要调用了三个函数: createComponentInstance(创建组件实例)、setupCompone
- 目录现象根因分析getLastPacketReceivedTimeMs()方法调用时机解决方案现象应用升级MySQL驱动8.0后,在并发量较
- 问题: 1. 后台管理员只有一个用户: admin, 密码: admin 2. 当管理员登陆成功后, 可以管理前台会员信
- 一、简介urllib 库,它是 Python 内置的 HTTP 请求库,不需要额外安装即可使用,它包含四个模块:`request` 请求模块
- 本文环境是python3,采用的是urllib,BeautifulSoup搭建。说下思路,这个项目分为管理器,url管理器,下载器,解析器,