Welcome, guest | Sign In | My Account | Store | Cart

WxFileRenamer is a small GUI utility for renaming files in a directory with regular expressions, which allows the user to preview the changes before committing them to disk.

Python, 226 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
"""
WxFileRenamer is a small GUI utility for renaming files in a directory
with regular expressions. The dialog consists of a console window for
text feedback followed by the three text fields: Dir, Search, and Replace
plus buttons for Simulate, Execute, and Quit.

Instructions:

* Use the command line or drag'n'drop to run WxFileRenamer with the path 
to a file whose name is to be changed.

* The directory path will appear in the Dir text field. The filename will
appear in the Search and Replace fields.

* Modify the Search and Replace regular expressions as desired.

* Click "Simulate" button to view effects of current Search and Replace
expressions on directory files without actually renaming files.

* Click "Execute" button to rename files according to Search and Replace
expressions.

* Click "Quit" button or select File\Quit from menu to exit application.

Requires wxPython -- download from http://www.wxpython.org/download.php.

Jack Trainor 2008
"""
import sys
import os, os.path
import re
import wx

DialogWidth = 1000
DialogHeight = 800

""" Utility class for renaming files and displaying results to output. """
class FileRenamer(object):
    def __init__(self, dir, matchRe, replaceRe, output, simulate=True):
        self.dir = dir
        self.output = output
        self.matchPat = re.compile(matchRe)
        self.replaceRe = replaceRe
        self.simulate = simulate
            
    def renamePath(self, path, newPath): 
        try:
            absPath = os.path.abspath(path)
            os.chmod(absPath, 0666)
            os.rename( absPath, newPath )
        except Exception, e:
            self.output('RenamePath failed: %s, %s' % (path, newPath))
    
    def execute(self):
        fileNames = os.listdir(self.dir)
        for fileName in fileNames:
            if self.matchPat.match(fileName):
                newName = self.matchPat.sub(self.replaceRe, fileName)
                self.output("%s -> %s\n" % (fileName, newName))
                if not self.simulate:
                    path = os.path.join(self.dir, fileName)
                    newPath = os.path.join(self.dir, newName)
                    self.renamePath(path, newPath)
        return self 

""" Wx utils """    
def CreateMenuBar(frame):
    menuBar = wx.MenuBar()
    frame.SetMenuBar(menuBar)
    return menuBar

def CreateMenu(menuBar, menuTitle):
    menu = wx.Menu()
    menuBar.Append(menu, menuTitle)
    return menu

def CreateMenuItem(frame, menu, id, itemTitle, statusMsg, method):
    menu.Append(id, itemTitle, statusMsg)
    frame.Bind(wx.EVT_MENU, method, id=id)

def CreateButton(frame, panel, buttonTitle, method, id=wx.ID_ANY):
    button = wx.Button(panel, id, buttonTitle)
    frame.Bind(wx.EVT_BUTTON, method, button)
    return button

def CreateLabeledTextSizer(staticText, textCtrl, proportion=0, flag=wx.ALL, border=5):
    sizer = wx.BoxSizer(wx.HORIZONTAL)
    sizer.Add(staticText, 0, wx.ALL, 5 )
    sizer.Add(textCtrl, 0, wx.ALL, 5 )
    return sizer
    
""" Wx app """
class FileRenamePanel(wx.Panel):
    LABEL_WIDTH = 50
    ENTRY_WIDTH = DialogWidth-100
    def __init__(self, parent, id=wx.ID_ANY):
        wx.Panel.__init__(self, parent, id)

        dir = searchText = ""
        path = parent.app.path
        if os.path.exists(path):
            if os.path.isdir(path):
                dir = path
                fileNames = os.listdir(dir)
                if fileNames:
                    fileNames.sort()
                    searchText = fileNames[0]
            elif os.path.isfile(path):
                dir, searchText = os.path.split(path)
        replaceText = searchText
        
        self.consoleText = wx.TextCtrl(self, -1, "", size=(DialogWidth-20, DialogHeight-220), style=wx.TE_MULTILINE)       

        dirLabel = wx.StaticText(self, -1, "Dir:", size=(FileRenamePanel.LABEL_WIDTH, -1), style=wx.ALIGN_RIGHT)
        self.dirEntry = wx.TextCtrl(self, -1, dir, wx.DefaultPosition, wx.Size(FileRenamePanel.ENTRY_WIDTH, -1))
        self.dirEntry.SetFont(wx.Font(-1, -1, wx.NORMAL, wx.BOLD))
        
        searchLabel = wx.StaticText(self, -1, "Search:", size=(FileRenamePanel.LABEL_WIDTH, -1), style=wx.ALIGN_RIGHT)
        self.searchEntry = wx.TextCtrl(self, -1, searchText , wx.DefaultPosition, wx.Size(FileRenamePanel.ENTRY_WIDTH, -1))
        self.searchEntry.SetFont(wx.Font(-1, -1, wx.NORMAL, wx.BOLD))

        replaceLabel = wx.StaticText(self, -1, "Replace:", size=(FileRenamePanel.LABEL_WIDTH, -1), style=wx.ALIGN_RIGHT)
        self.replaceEntry = wx.TextCtrl(self, -1, replaceText, wx.DefaultPosition, wx.Size(FileRenamePanel.ENTRY_WIDTH, -1))
        self.replaceEntry.SetFont(wx.Font(-1, -1, wx.NORMAL, wx.BOLD))
        
        self.simulateButton = CreateButton(parent, self, "Simulate", parent.OnSimulate)
        self.executeButton = CreateButton(parent, self, "Execute", parent.OnExecute)
        self.quitButton = CreateButton(parent, self, "Quit", parent.OnQuit)
        
        buttonSizer = wx.BoxSizer( wx.HORIZONTAL )
        buttonSizer.Add(self.simulateButton, 0, wx.ALL, 5 )
        buttonSizer.Add(self.executeButton, 0, wx.ALL, 5 )
        buttonSizer.Add(self.quitButton, 0, wx.ALL, 5 )
        
        sizer = wx.BoxSizer( wx.VERTICAL )
        sizer.Add(self.consoleText, 0, wx.ALL, 5 )
        sizer.Add(CreateLabeledTextSizer(dirLabel, self.dirEntry), 0, wx.ALIGN_LEFT) 
        sizer.Add(CreateLabeledTextSizer(searchLabel, self.searchEntry), 0, wx.ALIGN_LEFT) 
        sizer.Add(CreateLabeledTextSizer(replaceLabel, self.replaceEntry), 0, wx.ALIGN_LEFT) 
        sizer.Add(buttonSizer, 0, wx.ALL, 5 )
        
        self.SetSizer(sizer)
        self.Layout()        

    def GetConsoleText(self):
        return self.consoleText.GetValue()

    def SetConsoleText(self, text):
        self.consoleText.SetValue(text)
        self.consoleText.SetSelection(0, 0)

    def GetDirText(self):
        return self.dirEntry.GetValue()

    def GetSearchText(self):
        return self.searchEntry.GetValue()

    def GetReplaceText(self):
        return self.replaceEntry.GetValue()


class FileRenameFrame(wx.Frame):
    def __init__(self, app, parent, title):
        self.app = app
        wx.Frame.__init__(self, parent, -1, title, pos=(0, 0), size=(DialogWidth, DialogHeight))
        self.CreateStatusBar()

        menuBar = CreateMenuBar(self)
        fileMenu = CreateMenu(menuBar, "&File")
        CreateMenuItem(self, fileMenu, wx.ID_EXIT, "Q&uit\tCtrl-Q", "Exit", self.OnTimeToClose)
        self.panel = FileRenamePanel(self)
    
    def OnInit(self):
        self.frame = frame = FileRenameFrame(self, None, "FileRename Dialog")
        self.SetTopWindow(frame)
        frame.Show(True)
        return True

    def OnSimulate(self, evt):
        self.Execute(True)

    def OnExecute(self, evt):
        self.Execute(False)
        
    def Execute(self, simulate=True):
        dir = self.panel.GetDirText()
        matchRe = self.panel.GetSearchText()
        replaceRe = self.panel.GetReplaceText()
        fileRenamer = FileRenamer(dir, matchRe, replaceRe, self.AppendConsoleText, simulate).execute()
        self.AppendConsoleText("\n")

    def OnQuit(self, evt):
        self.OnTimeToClose(evt)

    def OnTimeToClose(self, evt):
        self.Close()

    def GetConsoleText(self):
        return self.panel.GetConsoleText()

    def SetConsoleText(self, text):
        self.panel.SetConsoleText(text)

    def AppendConsoleText(self, text):
        self.panel.consoleText.AppendText(text)

class WxFileRenamer(wx.App):
    def __init__(self, path, redirect=True, fileName=None):
        self.path = path
        wx.App.__init__(self, redirect, fileName)
        
    def OnInit(self):
        self.frame = frame = FileRenameFrame(self, None, "WxFileRenamer")
        self.SetTopWindow(frame)
        frame.Show(True)
        return True
        
def main(path):
    app = WxFileRenamer(path, redirect=False)
    app.MainLoop()

if __name__ == '__main__':
    path = r""
    if len(sys.argv) > 1:
        path = sys.argv[1]
    main(path)

I want an easy, flexible way to rename a group of files without writing small programs or working from the command line. I want to use regular expressions instead of glob or DOS wildcards. I want to set this task up with a minimum of keystrokes and mouse actions. And most important, I want to be able to simulate my renaming strategies before committing the changes to disk.

Plus I prefer wx for a cross-platform work to Tk so I wanted to write this utility in wx. It's a decent example of wx programming that can be used as a skeleton for further utility apps.

In the future I might add an "Undo" button for undoing renames after clicking the "Execute" button.