Skip to content

Instantly share code, notes, and snippets.

@jareddlc
Created October 18, 2016 23:20
Show Gist options
  • Save jareddlc/edc16b6030132461e20399b8242b6f46 to your computer and use it in GitHub Desktop.
Save jareddlc/edc16b6030132461e20399b8242b6f46 to your computer and use it in GitHub Desktop.
Batch rename
import os
import re
from Tkinter import *
from tkFileDialog import *
from tkMessageBox import *
# Tkingter root widget
root = Tk()
# App title
root.title("List Batch Rename")
class App:
# class initialization
def __init__(self, master):
frame = Frame(master)
frame.pack()
# defining the buttons
self.buttonList = Button(frame, text="Select List", command=self.selectList).pack()
self.buttonDir = Button(frame, text="Select Dir", command=self.selectDir).pack()
self.labelPrefix = Label(frame, text="Prefix:").pack()
self.entryPrefix = Entry(frame)
self.entryPrefix.pack()
self.labelList = Label(frame, text="List:")
self.labelList.pack()
self.labelDir = Label(frame, text="Dir:")
self.labelDir.pack()
self.buttonRename = Button(frame, text="Rename", command=self.rename).pack()
# class methods
def selectList(self):
self.pathList = askopenfilename()
self.labelList.config(text='List: ' + self.pathList)
print self.pathList
def selectDir(self):
self.pathDir = askdirectory()
self.labelDir.config(text='Dir: ' + self.pathDir)
print self.pathDir
def dialogError(self):
showerror("Error", "Please select List, Dir, and Prefix")
def rename(self):
# error checking
if not hasattr(self, 'pathList'):
self.dialogError()
return
if not hasattr(self, 'pathDir'):
self.dialogError()
return
if self.entryPrefix.get() == "":
self.dialogError()
return
# open file
f_file = open(self.pathList, 'r')
for line in f_file:
for dir_file in os.listdir(self.pathDir):
a = re.findall('\d{1,3}', line)
b = re.findall('\d{1,3}', dir_file)
if a == b:
new_name = self.entryPrefix.get() + '_' + dir_file
print new_name
# WARNING, NOT UNDOABLE! UNCOMMENT THE NEXT LINE TO RENAME YOUR FILES
# os.rename (dir_file, new_name)
f_file.close()
print "Done"
showinfo("Complete", "Batch rename complete")
app = App(root)
# enter Tkinger event loop
root.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment