Python实现文件夹内容对比:差异文件与相同文件处理示例

不晚
不晚
发布时间:2026-10-13| 3人浏览过
原创

本文介绍使用Python实现两个文件夹内容的对比功能,涵盖子目录遍历、差异文件列出及相同文件大小与内容比对。通过示例代码展示如何识别A比B多出的文件、B比A多出的文件,以及大小相同或不同的相同文件。

本文介绍如何使用Python实现两个文件夹内容的对比功能,包括对文件内容的详细比对。该示例可供参考学习。

#-*-coding:utf-8-*-
#===============================================================================
# 目录对比工具(包含子目录 ),并列出
# 1、A比B多了哪些文件
# 2、B比A多了哪些文件
# 3、二者相同的文件:文件大小相同 VS 文件大小不同 (Size相同文件不打印:与Size不同文件显示未排序)
#===============================================================================
import os, time,difflib
AFILES = [] #EE
BFILES = [] #SVN
COMMON = [] #EE & SVN
def getPrettyTime(state):
  return time.strftime('%y-%m-%d %H:%M:%S', time.localtime(state.st_mtime))
# def getpathsize(dir): #获取文件大小的函数,未用上,仅供学习.故注释掉
#   size=0
#   for root, dirs, files in os.walk(dir):
#   #root:目录:str 如: C:\CopySVN\SystemObject\TopoProcedure\Built-in\
#   #dirs:目录名称:列表: 如 ['Parsers']
#   #files:名称:列表: 如 ['011D0961FB42416AA49D5E82945DE7E9.og',...]
#   #file:目录:str, 如 011D0961FB42416AA49D5E82945DE7E9.og
#     for file in files:
#       path = os.path.join(root,file)
#       size = os.path.getsize(path)
#   return size
def dirCompare(apath,bpath):
  afiles = []
  bfiles = []
  for root, dirs , files in os.walk(apath):
    for f in files:
      afiles.append(root + "\\" + f)
  for root, dirs , files in os.walk(bpath):
    for f in files:
      bfiles.append(root + "\\" + f)
      #sizeB = os.path.getsize(root + "\\" + f) 此处定义的size无法在commonfiles进行比较. (A,B在各自的循环里面)
  # 去掉afiles中文件名的apath (拿A,B相同的路径\文件名,做成集合,去找交集)
  apathlen = len(apath)
  aafiles = []
  for f in afiles:
    aafiles.append(f[apathlen:])
  # 去掉bfiles中文件名的bpath
  bpathlen = len(bpath)
  bbfiles = []
  for f in bfiles:
    bbfiles.append(f[bpathlen:])
  afiles = aafiles
  bfiles = bbfiles
  setA = set(afiles)
  setB = set(bfiles)
  #print('%$%'+str(len(setA)))
  #print('%%'+str(len(setB)))
  commonfiles = setA & setB # 处理共有文件
  #print ("===============File with different size in '", apath, "' and '", bpath, "'===============")
  #将结果输出到本地
  #with open(os.getcwd()+'diff.txt','w') as di:
    #di.write("===============File with different size in '", apath, "' and '", bpath, "'===============")
  for f in sorted(commonfiles):
    sA=os.path.getsize(apath + "\\" + f)
    sB=os.path.getsize(bpath + "\\" + f)
    if sA==sB: #共有文件的大小比较
      #pass #print (f + "\t\t" + getPrettyTime(os.stat(apath + "\\" + f)) + "\t\t" + getPrettyTime(os.stat(bpath + "\\" + f)))
      #以下代码是处理大小一致,但是内容可能不一致的情况
      #print("in sa=sb")
      #print(os.getcwd())
      saf=[]
      sbf=[]
      sAfile=open(apath + "\\" + f)
      iter_f=iter(sAfile)
      for line in iter_f:
        saf.append(line)
      sAfile.close()
      sBfile=open(bpath + "\\" + f)
      iter_fb=iter(sBfile)
      for line in iter_fb:
        sbf.append(line)
      sBfile.close()
      saf1=sorted(saf)
      sbf1=sorted(sbf)
      if(len(saf1)!=len(sbf1)):
        with open(os.getcwd()+'\\comment_diff.txt','a') as fp:
          print(os.getcwd())
          fp.write(apath + "\\" + f+" lines size not equal "+bpath + "\\" + f+'\n')
      else:
        for i in range(len(saf1)):
          #print("into pre")
          if(saf1[i]!=sbf1[i]):
            print('into commont')
            with open(os.getcwd()+'\\comment_diff.txt','a') as fp1:
              fp1.write(apath + "\\" + f+" content not equal "+bpath + "\\" + f+'\n')
              break
    else:
      with open (os.getcwd()+'\\diff.txt','a') as di:
        di.write("File Name=%s  EEresource file size:%d  != SVN file size:%d" %(f,sA,sB)+'\n')
      #print ("File Name=%s  EEresource file size:%d  != SVN file size:%d" %(f,sA,sB))
  # 处理仅出现在一个目录中的文件
  onlyFiles = setA ^ setB
  aonlyFiles = []
  bonlyFiles = []
  for of in onlyFiles:
    if of in afiles:
      aonlyFiles.append(of)
    elif of in bfiles:
      bonlyFiles.append(of)
  #print ("###################### EE resource ONLY ###########################")
  #print ("#only files in ", apath)
  for of in sorted(aonlyFiles):
    with open (os.getcwd()+'\\EEonly.txt','a') as ee:
      ee.write(of+'\n')
    #print (of)
  #print ("*"*20+"SVN ONLY+"+"*"*20)
  #print ("#only files in ", bpath)
  for of in sorted(bonlyFiles):
    with open (os.getcwd()+'\\svnonly.txt','a') as svn:
      svn.write(of+'\n')
    #print (of)
if __name__ == '__main__':
  FolderEE = 'D:\\search\\bb\\ObjectGroup - Copy\\ObjectGroup\\Built-in'
  FolderSVN = 'D:\\search\\bb\\ObjectGroup\\ObjectGroup\\Built-in'
  dirCompare(FolderEE, FolderSVN)
  print("done!")

此外,推荐一款功能类似的在线工具供参考:

在线文本比较工具: http://tools.jb51.net/aideddesign/txt_diff

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。