- TODO function实现的功能
- 递归的比较两个目录 输出md5不相同的文件
- 若文件值不是MD5进行MD5值的转换
- 目录对比工具(包含子目录 ),并列出
- A比B多了哪些文件
- B比A多了哪些文件
- 二者相同的文件: md5比较
```python
# ===============================================================================
# TODO function实现的功能
# 1.递归的比较两个目录 输出md5不相同的文件
# 2.若文件值不是MD5进行MD5值的转换
# 3.目录对比工具(包含子目录 ),并列出
# 4.A比B多了哪些文件
# 5.B比A多了哪些文件
# 6.二者相同的文件: md5比较
# ===============================================================================
import os
import time
import difflib
import hashlib
# 获取md5值,如果文件不是MD5值要先获取MD5值
def getFileMd5(filename):
if not os.path.isfile(filename):
print('file not exist: ' + filename)
return
myhash = hashlib.md5()
f = open(filename, 'rb')
while True:
b = f.read(8096)
# print(b)
if not b:
break
myhash.update(b)
f.close()
return myhash.hexdigest()
# 获取所有文件的路径,这里实现内部文件夹路径
def getAllFiles(path):
flist = []
for root, dirs, fs in os.walk(path):
for f in fs:
f_fullpath = os.path.join(root, f)
f_relativepath = f_fullpath[len(path):]
flist.append(f_relativepath)
return flist
def dirCompare(apath, bpath):
afiles = getAllFiles(apath)
print(afiles)
bfiles = getAllFiles(bpath)
print(bfiles)
#排序
setA = set(afiles)
print(setA)
setB = set(bfiles)
print(setB)
#比较相同的文件(相同的文件)
commonfiles = setA & setB # 处理共有文件
print(commonfiles)
#TODO 处理相同文件,每个文件的为md5格式
for f in sorted(commonfiles):
amd = getFileMd5(apath + '\\' + f)
print(amd)
bmd = getFileMd5(bpath + '\\' + f)
print(bmd)
if amd != bmd:
print("dif file: %s文件名相同,文件的MD5值不相等" % (f))
else:
print("dif file: %s,文件名相同,文件的MD5值相等" % (f))
# 处理仅出现在一个目录中的文件
onlyFiles = setA ^ setB
print("仅出现在一个文件夹",onlyFiles)
onlyInA = []
onlyInB = []
for of in onlyFiles:
if of in afiles:
onlyInA.append(of)
elif of in bfiles:
onlyInB.append(of)
# 取A每一个文件,逐一与B的每一个文件进行对比,输出两文件MD5不相同的A文件
if len(onlyInA) > 0:
print('-' * 20, "only in ", apath, '-' * 20)
for of in sorted(onlyInA):
print(of)
if len(onlyInB) > 0:
print('-' * 20, "only in ", bpath, '-' * 20)
for of in sorted(onlyInB):
print(of)
#直接比较
def compare_a_b(apath, bpath):
afiles = getAllFiles(apath)
# print(afiles)
bfiles = getAllFiles(bpath)
# print(bfiles)
for a in afiles:
amd5=getFileMd5(apath + '\\' + a)
for b in bfiles :
bmd5=getFileMd5(bpath + '\\' + b)
if amd5 == bmd5:
print("a的文件名(直接比较)",a)
if __name__ == '__main__':
a=getFileMd5("E://eg.txt")
print(a)
aPath = os.getcwd() + '/a'
bPath = os.getcwd() + '/b'
dirCompare("E://dir","E://dire")
compare_a_b("E://dir", "E://dire")
用到了os.walk的使用,
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
top -- 是你所要遍历的目录的地址, 返回的是一个三元组(root,dirs,files)。
root 所指的是当前正在遍历的这个文件夹的本身的地址
dirs 是一个 list ,内容是该文件夹中所有的目录的名字(不包括子目录)
files 同样是 list , 内容是该文件夹中所有的文件(不包括子目录)
topdown --可选,为 True,则优先遍历 top 目录,否则优先遍历 top 的子目录(默认为开启)。如果 topdown 参数为 True,walk 会遍历top文件夹,与top 文件夹中每一个子目录。
onerror -- 可选,需要一个 callable 对象,当 walk 需要异常时,会调用。
followlinks -- 可选,如果为 True,则会遍历目录下的快捷方式(linux 下是软连接 symbolic link )实际所指的目录(默认关闭),如果为 False,则优先遍历 top 的子目录