Python工具-文件夹对比

本文介绍了一个简单的Python脚本,用于对比两个文件夹内的文件,并输出共有的文件及其最后修改时间,以及只存在于其中一个文件夹的文件。利用Python的set功能实现了高效比较。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件夹对比,意思是说对比两个文件夹,看他们里面哪些文件是共有的,哪些是单独所有的。

比如说这里对比d:/a文件夹和d:/b文件夹。最终输出共有的文件【对于共有的文件输出各自的最后修改时间】和单独拥有的文件。

代码如下:

#-*-coding:utf-8-*-  

#===============================================================================
# 目录对比工具,列出
# 1、A比B多了哪些文件
# 2、B比A多了哪些文件
# 3、二者相同的文件,如果最后修改日期不同,则要标注
# 4、包含子目录
#===============================================================================

import os, time

AFILES = []
BFILES = []
COMMON = []
def getPrettyTime(state):
    return time.strftime('%y-%m-%d %H:%M:%S', time.localtime(state.st_mtime))
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)
    #===========================================================================
    # 去掉afiles中文件名的apath
    #===========================================================================
    apathlen = len(apath)
    aafiles = []
    for f in afiles:
        aafiles.append(f[apathlen:])
    #===========================================================================
    # 去掉afiles中文件名的apath
    #===========================================================================
    bpathlen = len(bpath)
    bbfiles = []
    for f in bfiles:
        bbfiles.append(f[bpathlen:]) 
    afiles = aafiles
    bfiles = bbfiles
    setA = set(afiles)
    setB = set(bfiles)
    #===========================================================================
    # 处理共有文件
    #===========================================================================
    commonfiles = setA & setB
    print "#================================="
    print "common in '", apath, "' and '", bpath, "'"
    print "#================================="
    print '\t\t\ta:\t\t\t\t\t\tb:'
    for f in sorted(commonfiles):
        print f + "\t\t" + getPrettyTime(os.stat(apath + "\\" + f)) + "\t\t" + getPrettyTime(os.stat(bpath + "\\" + f))
        
    #===========================================================================
    # 处理仅出现在一个目录中的文件
    #===========================================================================
    onlyFiles = setA ^ setB
    aonlyFiles = []
    bonlyFiles = []
    for of in onlyFiles:
        if of in afiles:
            aonlyFiles.append(of)
        elif of in bfiles:
            bonlyFiles.append(of)
    print "#================================="
    print "#only in ", apath
    print "#================================="
    for of in sorted(aonlyFiles):
        print of
    print "#================================="
    print "#only in ", bpath
    print "#================================="
    for of in sorted(bonlyFiles):
        print of
if __name__ == '__main__':
    dirCompare('d:/a', 'd:/b')

运行结果如下:


其实实现起来还蛮简单的,因为python自身太强大。主要是用了python的set的功能。

a = t | s            # t 和 s的并集 

b = t & s          # t 和 s的交集 

c = t – s          # 求差集(项在t中,但不在s中) 

d = t ^ s          # 对称差集(项在t或s中,但不会同时出现在二者中)

----------------------------

在python中实际上本来就有这样的工具。filecmp模块就是做这个工作的。

filecmp模块有cmp(file1,file2)、cmpfiles(dir1,dir2)、dircmp(dir1,dir2)等几个函数可以使用。

# -*- coding: utf-8 -*- ''' 事件传播有两种类型事件:基本事件和命令事件。它们不同于传播方式。事件传播是指事件从子部件 传到父部件和父窗口的父窗口等。基本事件不传播,命令事件传播。比如wx.CloseEvent是一个基本事件。 它没有传到父窗口的一样。默认情况下, 这种事件在一个事件处理器里就停止传播。如果想继续传播, 我们必须调用Skip()方法。 用event.Skip()方法调用事件默认处理程序 ''' import wx import threading from os.path import getsize def CompFile(win,file1,file2): try: if getsize(file1) != getsize(file2): win.m_staticText4.SetFont(win.font) win.m_staticText4.SetForegroundColour(wx.Colour(255,0,0)) win.m_staticText4.SetLabelText('文件比较结果:两个文件比较结果不一样') win.m_button4.SetFocus() win.m_button4.SetDefault() return f1=open(file1,'rb') f2=open(file2,'rb') except Exception as e: win.m_staticText4.SetFont(win.font) win.m_staticText4.SetForegroundColour(wx.Colour(255,0,255)) win.m_staticText4.SetLabelText('打开文件错误:'+e.strerror) win.m_button4.SetFocus() win.m_button4.SetDefault() else: for f11,f22 in zip(f1.read(),f2.read()): if f11 != f22: win.m_staticText4.SetFont(win.font) win.m_staticText4.SetForegroundColour(wx.Colour(255,0,0)) win.m_staticText4.SetLabelText('文件比较结果:两个文件比较结果不一样') win.m_button4.SetFocus() win.m_button4.SetDefault() return else: win.m_staticText4.SetFont(win.font) win.m_staticText4.SetForegroundColour(wx.Colour(0,155,0)) win.m_staticText4.SetLabelText('文件比较结果:两个文件比较结果一模一样') win.m_button4.SetFocus() win.m_button4.SetDefault() finally: try: f1.close() f1.close() except: pass class FileDrop(wx.FileDropTarget): def __init__(self, textctrl): wx.FileDropTarget.__init__(self) self.textctrl = textctrl def OnDropFiles(self, x, y, filePath): # 当文件被拖入grid后,会调用此方法 self.textctrl.SetValue(''.join(filePath)) return 1 class Mywin(wx.Dialog): def __init__(self,parent,title): super().__init__(parent,title=title,size=(500,200),style=wx.DEFAULT_FRAME_STYLE|wx.STAY_ON_TOP) self.InitUI() def InitUI(self): icon = wx.Icon('33.ico', wx.BITMAP_TYPE_ICO) self.SetIcon(icon) self.SetSizeHints( wx.DefaultSize, wx.DefaultSize ) bSizer7 = wx.BoxSizer( wx.VERTICAL ) bSizer8 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText2 = wx.StaticText( self, wx.ID_ANY, u"第一个文件", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText2.Wrap( -1 ) bSizer8.Add( self.m_staticText2, 0, wx.ALL, 10 ) self.m_textCtrl3 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_textCtrl3.Bind(wx.EVT_TEXT_ENTER,self.onTextChange) self.fileDrop = FileDrop(self.m_textCtrl3) self.m_textCtrl3.SetDropTarget(self.fileDrop) bSizer8.Add( self.m_textCtrl3, 1, wx.ALL, 5 ) bSizer7.Add( bSizer8, 0, wx.EXPAND, 5 ) bSizer9 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText3 = wx.StaticText( self, wx.ID_ANY, u"第二个文件", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText3.Wrap( -1 ) bSizer9.Add( self.m_staticText3, 0, wx.ALL, 10 ) self.m_textCtrl4 = wx.TextCtrl( self, 5001, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) self.fileDrop1 = FileDrop(self.m_textCtrl4) self.m_textCtrl4.SetDropTarget(self.fileDrop1) bSizer9.Add( self.m_textCtrl4, 1, wx.ALL, 5 ) bSizer7.Add( bSizer9, 0, wx.EXPAND, 5 ) bSizer11 = wx.BoxSizer( wx.HORIZONTAL ) self.m_button4 = wx.Button( self, wx.ID_ANY, u"文件比较", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_button4.Bind(wx.EVT_BUTTON,self.OnButton) self.m_button4.SetFocus() self.m_button4.SetDefault() bSizer11.Add( self.m_button4, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 5 ) self.m_button5 = wx.Button( self, wx.ID_ANY, u"清空文本", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_button5.Bind(wx.EVT_BUTTON,self.OnClear) bSizer11.Add( self.m_button5, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 5 ) bSizer7.Add( bSizer11, 0, wx.ALIGN_CENTER|wx.ALIGN_LEFT, 5 ) bSizer12 = wx.BoxSizer( wx.VERTICAL ) self.font=wx.Font(16,wx.ROMAN,wx.NORMAL,wx.NORMAL) self.font.FaceName="微软雅黑" self.m_staticText4 = wx.StaticText( self, wx.ID_ANY, u"文件比较结果:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText4.SetFont(self.font) self.m_staticText4.Wrap( -1 ) bSizer12.Add( self.m_staticText4, 0, wx.ALL, 5 ) bSizer7.Add( bSizer12, 1, wx.EXPAND, 5 ) self.SetSizer( bSizer7 ) self.Layout() self.Bind(wx.EVT_CLOSE,self.onClose) self.Centre( wx.BOTH ) self.Show() def onTextChange(self,evt): self.m_button4.SetFocus() self.m_button4.SetDefault() def OnButton(self,event): file1=self.m_textCtrl3.GetValue() file2=self.m_textCtrl4.GetValue() t1=threading.Thread(target=CompFile,args=(self,file1,file2),name="CompFile") t1.start() self.m_staticText4.SetLabelText('正在比较文件请稍后!...') #CompFile(self,file1,file2) def OnClear(self,event): self.m_staticText4.SetForegroundColour(wx.Colour(0,0,0)) self.m_staticText4.SetLabelText('文件比较结果:') self.m_textCtrl3.SetValue('') self.m_textCtrl4.SetValue('') self.m_button4.SetFocus() self.m_button4.SetDefault() def onClose(self,e): self.Destroy() app=wx.App() Mywin(None,'文件比较') app.MainLoop()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值