-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
381 lines (311 loc) · 16.6 KB
/
main.py
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
#imports
from tkinter import ttk, filedialog
import tkinter as tk
import threading, os, time, subprocess
class Execution():
def changeFolder(self):
"""Simply changes the current working directory
"""
os.chdir(filedialog.askdirectory() + "/")
def createFolders(self, inputString: str, timeSleep: int, numIterations=0, startPos=0):
"""Create folders named after the names specified
Args:
inputString (str): Folders names
timeSleep (int): Pause time between folder creation
numIterations (int): Number of iterations; 0 means it's disabled and >0 create the amount of folders and increments the value of '{inc}' from <startPos> to it. Defaults to 0.
startPos (int, optional): pos to start from if iteration mode selcted. Defaults to 0.
"""
self.functionsOutput = ""
inputList = inputString.split("\n")
if numIterations == 0:
for item in inputList:
try:
os.mkdir(item)
time.sleep(timeSleep)
self.functionsOutput = "Done!\n"
except Exception as error:
if str(error).startswith("[WinError 183]"):
self.functionsOutput = f"'{item}' already exist (skipping)\n"
elif str(error).startswith("[WinError 123]"):
self.functionsOutput = f"'{item}' has invalid name (skipping)\n"
else:
self.functionsOutput = str(error) + "\n"
else:
try:
for iteration in range(numIterations):
for item in inputList:
for j in range(len(item)):
marker = item[j:j+5]
if marker == "{inc}":
os.mkdir(f"{item[0:j]}{iteration+startPos}{item[j+5:len(item)]}")
time.sleep(timeSleep)
self.functionsOutput = "Done!\n"
except Exception as error:
print(error)
if str(error).startswith("[WinError 183]"):
self.functionsOutput = f"'{item}' already exist (skipping)\n"
elif str(error).startswith("[WinError 123]"):
self.functionsOutput = f"'{item}' has invalid name (skipping)\n"
elif str(error).endswith("object cannot be interpreted as an integer"):
self.functionsOutput = "Please only use integers as increment values\n"
else:
self.functionsOutput = str(error) + "\n"
def removeFolders(self, inputString:int, modeSelected:int, startsEndsWith:str, numIterations=0, startPos=0):
"""Remove folders named after the specified names
Args:
inputString (int): Folders names
modeSelected (int): 1 is 'starts with', 2 is 'ends with' and 0 is normal/iteration
startsEndsWith (str): Charactes passed as params is modeSelected is 1 or 2
numIterations (int, optional): 0 is no iteration and >0 loops replacing '{inc}' by the loop index. Defaults to 0.
startPos (int, optional): pos to start from if iteration mode selcted. Defaults to 0.
"""
self.functionsOutput = ""
inputList = inputString.split("\n")
if modeSelected == 0:
self.functionsOutput = ""
inputList = inputString.split("\n")
if numIterations == 0:
for folder in inputList:
try:
os.rmdir(folder)
self.functionsOutput = "Done!\n"
except Exception as error:
if str(error).startswith("[WinError 2]"):
self.functionsOutput = f"'{folder}' doesn't exist (skipping)\n"
elif str(error).startswith("[WinError 3]"):
pass
else:
self.functionsOutput = str(error) + "\n"
else:
for iteration in range(numIterations):
for folder in inputList:
try:
for j in range(len(folder)):
marker = folder[j:j+5]
if marker == "{inc}":
os.rmdir(f"{folder[0:j]}{iteration+startPos}{folder[j+5:len(folder)]}")
self.functionsOutput = "Done!\n"
except Exception as error:
if str(error).startswith("[WinError 2]"):
self.functionsOutput = f"'{folder}' doesn't exist (skipping)\n"
elif str(error).startswith("[WinError 3]"):
pass
else:
self.functionsOutput = str(error) + "\n"
elif modeSelected == 1:
if startsEndsWith == "":
return
for it in os.listdir(os.getcwd()):
if os.path.isdir(it) and it.startswith(startsEndsWith):
print(it)
os.rmdir(it)
self.functionsOutput = "Done!\n"
elif modeSelected == 2:
if startsEndsWith == "":
return
for it in os.listdir(os.getcwd()):
if os.path.isdir(it) and it.endswith(startsEndsWith):
os.rmdir(it)
self.functionsOutput = "Done!\n"
def modifyFolders(self, inputString:str, modeSelected:int, replaceWith:str, timeSleep:int):
for it in os.listdir(os.getcwd()):
if os.path.isdir(it):
try:
time.sleep(timeSleep)
if it.startswith(inputString) and modeSelected == 1:
prefix = it[:len(inputString)]
suffix = it[len(inputString):]
os.rename(it, prefix.replace(inputString, replaceWith) + suffix)
elif it.endswith(inputString) and modeSelected == 2:
if inputString == "":
os.rename(it, it + replaceWith)
elif replaceWith == "":
os.rename(it, it[:-len(inputString)])
else:
prefix = it[:-len(inputString)]
suffix = it[-len(inputString)]
os.rename(it, prefix + suffix.replace(inputString, replaceWith))
self.functionsOutput = "Done!\n"
except Exception as error:
self.functionsOutput = str(error) + "\n"
def getFolderList(self):
self.foldersList = ""
for it in os.listdir(os.getcwd()+"/"):
if os.path.isdir(it):
self.foldersList = self.foldersList + it +"\n"
#UI class
class WindowUI:
def __init__(self):
self.execution = Execution()
#global
width = 700
height = 600
self.root = tk.Tk()
self.root.geometry(f"{width}x{height}")
self.root.title("Mass Directory Manager")
tabControl = ttk.Notebook(self.root)
anotherTabControl = ttk.Notebook(self.root)
self.tab1 = tk.Frame(tabControl)
self.tab2 = tk.Frame(tabControl)
self.tab3 = tk.Frame(tabControl)
self.tab4 = tk.Frame(anotherTabControl)
tabControl.add(self.tab1, text = " Create folders ")
tabControl.add(self.tab2, text = " Remove folders ")
tabControl.add(self.tab3, text = " Modify folders ")
tabControl.pack(side = "left", anchor = "n", expand=True, fill=tk.BOTH)
anotherTabControl.add(self.tab4, text = "Output")
anotherTabControl.pack(side = "right", anchor = "n", expand=True, fill=tk.BOTH)
self.root.bind("<Escape>", lambda y: self.root.geometry(f"{width}x{height}"))
self.root.bind("<F1>", lambda z: tabControl.select(self.tab1))
self.root.bind("<F2>", lambda z: tabControl.select(self.tab2))
self.root.bind("<F3>", lambda z: tabControl.select(self.tab3))
#tab1 - create folders
textBox1 = tk.Text(self.tab1, width = 40)
textBox1.pack(expand=True, fill=tk.BOTH)
buttonGo1 = tk.Button(self.tab1, text = "Go!", command = lambda: [self.newCreateFolders(textBox1.get("1.0",'end-1c'), v1.get())])
buttonGo1.pack(side = "bottom", pady = 10)
v1 = tk.DoubleVar()
timeoutText = tk.Label(self.tab1, text = "Time to pause between actions (in seconds)")
timeoutText.pack()
timeoutSlider = tk.Scale(self.tab1, variable = v1, from_ = 0, to = 60, orient = tk.HORIZONTAL)
timeoutSlider.pack(anchor = tk.CENTER, expand=True, fill=tk.BOTH)
self.incrementVariable = tk.IntVar()
incrementButton1 = tk.Checkbutton(self.tab1, text = "Increment mode", variable = self.incrementVariable, onvalue = 1, offvalue = 0, command = lambda: [self.incrementSelector(self.tab1)])
incrementButton1.pack(side = "left", anchor = "sw")
#tab2 - remove folders
testBox2 = tk.Text(self.tab2, width = 40)
testBox2.pack(expand=True, fill=tk.BOTH)
v4 = tk.IntVar()
startsWith1 = tk.Checkbutton(self.tab2, text = "Starts with", variable=v4, onvalue=1, offvalue=0)
startsWith1.pack()
endsWith1 = tk.Checkbutton(self.tab2, text = "Ends with", variable=v4, onvalue=2, offvalue=0)
endsWith1.pack()
entryBox1 = tk.Entry(self.tab2)
entryBox1.pack()
buttonGo2 = tk.Button(self.tab2, text = "Go!", command = lambda: [self.newRemoveFolders(testBox2.get("1.0",'end-1c'), v4.get(), entryBox1.get())])
buttonGo2.pack(side = "bottom", pady = 10)
incrementButton2 = tk.Checkbutton(self.tab2, text = "Increment mode", variable = self.incrementVariable, onvalue = 1, offvalue = 0, command = lambda: [self.incrementSelector(self.tab2)])
incrementButton2.pack(side = "left", anchor = "sw")
#tab3 - modify folders
v2 = tk.IntVar()
startsWith = tk.Checkbutton(self.tab3, text = "Starts with", variable=v2, onvalue=1, offvalue=0)
startsWith.pack()
endsWith = tk.Checkbutton(self.tab3, text = "Ends with", variable=v2, onvalue=2, offvalue=0)
endsWith.pack()
entryBox2 = tk.Entry(self.tab3)
entryBox2.pack()
replaceLabel = tk.Label(self.tab3, text = "Replace with:")
replaceLabel.pack()
entryBox3 = tk.Entry(self.tab3)
entryBox3.pack()
v3 = tk.DoubleVar()
timeoutText2 = tk.Label(self.tab3, text = "Time to pause between actions (in seconds)")
timeoutText2.pack()
timeoutSlider = tk.Scale(self.tab3, variable = v3, from_ = 0, to = 60, orient = tk.HORIZONTAL)
timeoutSlider.pack(anchor = tk.CENTER, expand=True, fill=tk.BOTH)
buttonGo3 = tk.Button(self.tab3, text = "Go!", command = lambda: [self.newModifyFolders(entryBox2.get(), v2.get(), entryBox3.get(), v3.get())])
buttonGo3.pack(side = "bottom", pady = 10)
#tab4 - output
self.logs = tk.Text(self.tab4, state = 'normal', wrap = 'none', width = 33)
self.logs.pack(expand=True, fill=tk.BOTH)
self.logs.configure(state = "disabled")
buttonClearLogs = tk.Button(self.tab4, text = "Clear logs", command = self.clearLogs)
buttonClearLogs.pack(padx = 10, pady = 5)
buttonFolderList = tk.Button(self.tab4, text = "Get folders list", command = self.newFoldersList)
buttonFolderList.pack(padx = 10, pady = 5)
buttonSelectFolder = tk.Button(self.tab4, text = "Change working folder", command = self.newChangeFolder)
buttonSelectFolder.pack(padx = 10, pady = 5)
buttonOpenFolder = tk.Button(self.tab4, text = "Explore working folder", command = self.newOpenCurrentFolder)
buttonOpenFolder.pack(padx = 10, pady = 5)
buttonQuit = tk.Button(self.tab4, text = "Quit!", command = self.root.destroy)
buttonQuit.pack(side = "bottom", anchor = "se", pady = 8, padx = 8)
def focus_next_widget(self, event):
event.widget.tk_focusNext().focus()
return("break")
def focus_previous_widget(self, event):
event.widget.tk_focusPrev().focus()
return("break")
def clearLogs(self):
self.logs.config(state=tk.NORMAL)
self.logs.delete('1.0', tk.END)
def incrementSelector(self, selectedTab):
variable = self.incrementVariable.get()
if variable == 1:
self.label1 = tk.Label(selectedTab, text= "Num to loop")
self.label1.pack(side="left", anchor="w", padx = 2, expand=True, fill=tk.BOTH)
self.incrementValue = tk.Text(selectedTab, height = 1, width = 3)
self.incrementValue.pack(side = "left", anchor="w", padx = 2, expand=True, fill=tk.BOTH)
self.incrementValue.bind("<Tab>", self.focus_next_widget)
self.label2 = tk.Label(selectedTab, text= "Pos to start")
self.label2.pack(side="left", anchor="e", padx = 2, expand=True, fill=tk.BOTH)
self.incrementStart = tk.Text(selectedTab, height = 1, width = 2)
self.incrementStart.pack(side = "left", anchor="e", padx = 2, expand=True, fill=tk.BOTH)
self.incrementStart.bind("<Tab>", self.focus_next_widget)
elif variable == 0:
try:
self.label1.destroy()
self.incrementValue.destroy()
self.label2.destroy()
self.incrementStart.destroy()
except:
pass
def newCreateFolders(self, entryGet = "", sleepValue = 0):
try:
incrementValue = self.incrementValue.get(1.0, "end-1c")
incrementStart = self.incrementStart.get(1.0, "end-1c")
except:
incrementValue = 0
incrementStart = 0
if incrementStart == "":
incrementStart = 1
if incrementValue == "":
incrementValue = 0
if str(incrementValue).isdigit():
incrementValue = int(incrementValue)
if str(incrementStart).isdigit():
incrementStart = int(incrementStart)
p = threading.Thread(target = self.execution.createFolders(entryGet, sleepValue, incrementValue, incrementStart))
p.start()
self.logs.configure(state = "normal")
self.logs.insert("1.0", f"---------------------------------\n{self.execution.functionsOutput}")
self.logs.configure(state = "disabled")
def newRemoveFolders(self, entryGet = "", modeSelected = 0, startsEndsWith = ""):
try:
incrementValue = self.incrementValue.get(1.0, "end-1c")
incrementStart = self.incrementStart.get(1.0, "end-1c")
except:
incrementValue = 0
incrementStart = 0
if incrementStart == "":
incrementStart = 1
if incrementValue == "":
incrementValue = 0
if str(incrementValue).isdigit():
incrementValue = int(incrementValue)
if str(incrementStart).isdigit():
incrementStart = int(incrementStart)
p = threading.Thread(target = self.execution.removeFolders(entryGet, modeSelected, startsEndsWith, incrementValue, incrementStart))
p.start()
self.logs.configure(state = "normal")
self.logs.insert("1.0", f"---------------------------------\n{self.execution.functionsOutput}")
self.logs.configure(state = "disabled")
def newModifyFolders(self, entryGet = "", modeSelected = 0, replaceWith = "", sleepValue = 0):
p = threading.Thread(target = self.execution.modifyFolders(entryGet, modeSelected, replaceWith, sleepValue))
p.start()
self.logs.configure(state = "normal")
self.logs.insert("1.0", f"---------------------------------\n{self.execution.functionsOutput}")
self.logs.configure(state = "disabled")
def newFoldersList(self):
p = threading.Thread(target = self.execution.getFolderList())
p.start()
self.logs.configure(state = "normal")
self.logs.insert("1.0", f"---------------------------------\nCurrently working on:\n{os.getcwd()}.\nFolders list:\n{self.execution.foldersList}")
self.logs.configure(state = "disabled")
def newChangeFolder(self):
p = threading.Thread(target = self.execution.changeFolder())
p.start()
def newOpenCurrentFolder(self):
subprocess.Popen(f'explorer "{os.getcwd()}"')
if __name__ == '__main__':
startUI = WindowUI()
startUI.root.mainloop()