-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileSorter.pyw
348 lines (292 loc) · 14.1 KB
/
FileSorter.pyw
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
# Welcome to FileSorter!
# This program will sort files, the way you want them sorted!
# Copyright © 2022 GeraldTM
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
import datetime,json, shutil, tkinter as tk, os
from posixpath import abspath
from tkinterdnd2 import DND_FILES, TkinterDnD
from tkinter import *
from tkinter import ttk, messagebox, filedialog
from PIL import Image,UnidentifiedImageError
if os.name == "nt":
newline = "\r\n"
else:
newline = "\n"
# Set up tkinter window
app = TkinterDnD.Tk()
app.title("FileSorter")
app.iconbitmap(True,"icon.ico")
app.resizable(width=False, height=False)
selectedSortType = StringVar()
selectedSortType.set("time")
fileListValue = StringVar()
keepOGFiles = BooleanVar()
# Init File Frame
fileFrame = ttk.Frame(app, padding="3 3 12 12")
fileFrame.grid(column=0, row=0, sticky=(N, W, E))
fileFrame.columnconfigure(0, weight=1)
fileFrame.rowconfigure(0, weight=1)
ttk.Label(fileFrame, text="Files to sort:").grid(column=0, row=0, sticky=W)
# Init Path input Frame
pathframe = ttk.Frame(fileFrame, padding="3 3 12 12")
pathframe.grid(column=0, row=2, sticky=(W, E))
ttk.Label(pathframe, text="Path: ").grid(column=1, row=0, sticky=W)
ttk.Button(pathframe, text="Browse", command=lambda: pathEntry.insert(0, filedialog.askdirectory())).grid(column=3, row=0, sticky=E)
pathEntry = ttk.Entry(pathframe, width=50)
pathEntry.grid(column=2, row=0, sticky=(W, E))
# Init Sort Path Frame
sortFrame = ttk.Frame(fileFrame, padding="3 3 12 12")
sortFrame.grid(column=0, row=3, sticky=(W, E))
ttk.Label(sortFrame, text="Sort to: ").grid(column=0, row=0, sticky=W)
ttk.Button(sortFrame, text="Browse", command=lambda: sortPath.insert(0, filedialog.askdirectory())).grid(column=2, row=0, sticky=E)
sortPath = ttk.Entry(sortFrame, width=50)
sortPath.grid(column=1, row=0, sticky=(W, E))
# Init Sort Type Frame
settingsFrame = ttk.Frame(app, padding="3 3 12 12")
settingsFrame.grid(column=1, row=0, sticky=(N, W, E, S))
ttk.Label(settingsFrame, text="Sort by:").grid(column=0, row=0, sticky=W)
ttk.Button(settingsFrame, text="Settings", command=lambda: messagebox.showerror("Error", "Settings not implemented yet!")).grid(column=1, row=0, sticky=E)
configFrame = ttk.Frame(settingsFrame, padding="3 3 12 12")
configFrame.grid(column=0, row=1, sticky=(W, E))
ttk.Radiobutton(configFrame, text="Sort by Date Created (Year)", variable=selectedSortType, value="time").grid(column=0, row=0, sticky=W)
ttk.Radiobutton(configFrame, text="Sort by Date Taken (Photos)", variable=selectedSortType, value="photo").grid(column=0, row=1, sticky=W)
#ttk.Radiobutton(configFrame, text="Sort by Name (A-Z)", variable=selectedSortType, value="name").grid(column=0, row=2, sticky=W)
keepOGButton = ttk.Checkbutton(configFrame, text="Keep original files", variable= keepOGFiles, onvalue=True, offvalue=False)
keepOGButton.grid(column=0, row=3, sticky=W)
buttonframe = ttk.Frame(settingsFrame, padding="3 3 12 12")
buttonframe.grid(column=0, row=3, sticky=(S,W,E), columnspan= 2)
ttk.Button(buttonframe, text="Sort", command=lambda: sort()).grid(column=1, row=0, sticky=(E,S))
ttk.Label(buttonframe, text="Copyright © GeraldTM 2022").grid(column=0, row=0, sticky=(W,S))
fileList = tk.Listbox(fileFrame, width=75, height=30, listvariable = fileListValue)
fileList.insert(0,"drop files here")
fileList.drop_target_register(DND_FILES)
fileList.dnd_bind('<<Drop>>', lambda e: dataToOutput(e.data))
fileList.grid(column=0, row=1, sticky=(N, W, E, S))
def dataToOutput(data):
"".join(data)
dlist = str(data.replace("{", "").replace("}", ",").replace("'", "").replace('"', "").replace("(","")).split(",")
for e in dlist:
if (fileList.get(0) == "drop files here"):
fileList.delete(0)
fileList.insert(tk.END, e)
def dataToList(data):
dlist = data.replace("{", "").replace("'", "").replace('"', "").replace("(","").replace(")","")
print(dlist)
dlist = "".join(dlist)
dlist = list(dlist.split(", "))
dlist[len(dlist)-1] = dlist[len(dlist)-1].replace(", ", "")
return dlist
def sort():
if (pathEntry.get() == "" and fileListValue.get() == "('drop files here',)"):
messagebox.showerror("Error", "No files to sort!")
elif(pathEntry.get() == "" and fileListValue.get() != "('drop files here',)"):
sortByList(fileListValue.get(), sortPath.get())
elif(pathEntry.get() != "" and fileListValue.get() == "('drop files here',)"):
sortByPath(pathEntry.get(), sortPath.get())
elif (pathEntry.get() != "" and fileListValue.get() != "('drop files here',)"):
sortByList(fileListValue.get(), sortPath.get())
sortByPath(pathEntry.get(), sortPath.get())
fileList.delete(0, tk.END)
fileList.insert(0, "drop files here")
def sortByList(files, pathto):
files = dataToList(files)
print(files)
if(pathto == ""):
messagebox.showerror("Error", "No path to sort to!")
else:
if(selectedSortType.get() == "time"):
sortByYear(files, pathto)
elif(selectedSortType.get() == "photo"):
sortByEXIF(files, pathto)
elif(selectedSortType.get() == "name"):
sortByName()
def listdirpath(path):
return [str(os.path.join(path, f)) for f in os.listdir(path)]
def sortByPath(path, pathto):
files = listdirpath(path)
if(pathto == ""):
pathto = pathEntry.get()
if(selectedSortType.get() == "time"):
sortByYear(files, pathto)
elif(selectedSortType.get() == "photo"):
sortByEXIF(files, pathto)
elif(selectedSortType.get() == "name"):
sortByName()
def sortByYear(files, pathto):
blacklist = []
# Get sort path
# get percentage of files
try:
progressInterval = 100/len(files)
except ZeroDivisionError:
progressInterval = 100
# Init progress bar
ttk.Label(sortFrame, text="Sorting: ").grid(column=0, row=0, sticky=W)
sortProgress = ttk.Progressbar(sortFrame, orient="horizontal", length=200, mode="determinate")
sortProgress.grid(column=1, row=0, sticky=(W,E))
# Sort files
errors = 0
for file in list(files):
print(file)
try:
date = datetime.datetime.fromtimestamp(os.path.getctime(file)).strftime("%Y")
except PermissionError as e:
messagebox.showerror("Error", "Permission denied!" + newline + str(e))
errors += 1
continue
except FileNotFoundError as e:
messagebox.showerror("Error", "File not found!" + newline + str(e))
errors += 1
continue
# Create folder if it doesn't exist
if pathto + "\\" + date not in blacklist:
try:
os.mkdir(pathto + "\\" + date)
except FileExistsError:
pass
except FileNotFoundError:
try:
os.mkdir(pathto)
os.mkdir(pathto + "\\" + date)
except FileNotFoundError as e:
messagebox.showerror("Error", "Path not found!" + pathto +newline + e)
break
except PermissionError as e:
messagebox.showerror("Error", "Permission denied!" + newline + e)
break
blacklist.append(pathto + "\\" + date)
# Move file to folder
if keepOGFiles.get():
try:
shutil.copy2(file, pathto + "\\" + date + "\\" + os.path.basename(file))
except PermissionError:
try:
shutil.copytree(file, pathto + "\\" + date + "\\" + os.path.basename(file))
except shutil.Error as e:
messagebox.showerror("Error", "Failed to move file: " + os.path.basename(file) + " to " + pathto + "\\" + date + "\\" + os.path.basename(file) + "newline newline" + str(e))
errors += 1
except shutil.Error as e :
messagebox.showerror("Error", "Failed to move file: " + os.path.basename(file) + " to " + pathto + "\\" + date + "\\" + os.path.basename(file) + "newline newline" + str(e))
errors += 1
else:
try:
shutil.move(file, pathto + "\\" + date + "\\" + os.path.basename(file), copy_function= shutil.copy2)
except shutil.Error as e:
messagebox.showerror("Error", "Failed to move file: " + os.path.basename(file) + " to " + pathto + "\\" + date + "\\" + os.path.basename(file) + "newline newline" + str(e))
errors += 1
sortProgress["value"] += progressInterval
sortProgress.update()
# Reset sort to path entry
ttk.Label(sortFrame, text="Sort to: ").grid(column=0, row=0, sticky=W)
sortPath = ttk.Entry(sortFrame, width=50)
sortPath.grid(column=1, row=0, sticky=(W, E))
#create finished dialog window
doneWindow = Toplevel(app)
doneWindow.title("Done!")
doneFrame = ttk.Frame(doneWindow, padding="3 3 12 12")
doneFrame.grid(column=3, row=0, sticky=(N, W, E, S))
doneWindow.columnconfigure(0, weight=1)
doneWindow.rowconfigure(0, weight=1)
ttk.Label(doneFrame, text="Sorting Complete! Sorted " + str(len(files)- errors) + " files.").grid(column=0, row=1, sticky=W)
ttk.Button(doneFrame, text="Close", command=doneWindow.destroy).grid(column=0, row=3, sticky=E)
def sortByEXIF(files, pathto):
# Get sort path
blacklist = []
# get percentage of files
try:
progressInterval = 100/len(files)
except ZeroDivisionError:
progressInterval = 100
# Init progress bar
ttk.Label(sortFrame, text="Sorting: ").grid(column=0, row=0, sticky=W)
sortProgress = ttk.Progressbar(sortFrame, orient="horizontal", length=200, mode="determinate")
sortProgress.grid(column=1, row=0, sticky=(W, E))
# Sort files
errors = 0
for file in list(files):
#Get photo taken date
try:
try:
date = datetime.datetime.fromtimestamp(Image.open(file).getexif().get(36867)).strftime("%Y")
except PermissionError:
try:
date = datetime.datetime.fromtimestamp(os.path.getctime(file)).strftime("%Y")
except PermissionError as e:
messagebox.showerror("Error", "Permission denied!" + newline + str(e))
errors += 1
continue
except TypeError as e:
#messagebox.showerror("Error", "Error reading EXIF data!" + newline + str(e))
date = datetime.datetime.fromtimestamp(os.path.getctime(file)).strftime("%Y")
except UnidentifiedImageError: # If file is not a photo
try:
date = datetime.datetime.fromtimestamp(os.path.getctime(file)).strftime("%Y")
except PermissionError as e:
messagebox.showerror("Error", "Permission denied!" + newline + str(e))
errors += 1
continue
blacklist.append(pathto + "\\" + date)
# Create folder if it doesn't exist
if pathto + "//" + os.path.basename(file) not in blacklist:
try:
os.mkdir(pathto + "\\" + date)
except FileExistsError:
pass
except FileNotFoundError:
try:
os.mkdir(pathto)
os.mkdir(pathto + "\\" + date)
except FileNotFoundError as e:
messagebox.showerror("Error", "Path not found!" + pathto +newline + e)
break
except PermissionError as e:
messagebox.showerror("Error", "Permission denied!" + newline + e)
continue
# Move file to folder
if keepOGFiles.get():
try:
shutil.copy2(file, pathto + "\\" + date + "\\" + os.path.basename(file))
except shutil.Error as e :
messagebox.showerror("Error", "Failed to move file: " + os.path.basename(file) + " to " + pathto + "\\" + date + "\\" + os.path.basename(file) + "newline newline" + str(e))
errors += 1
except PermissionError as e:
messagebox.showerror("Error", "Permission denied!" + newline + str(e))
errors += 1
else:
try:
shutil.move(file, pathto + "\\" + date + "\\" + os.path.basename(file), copy_function= shutil.copy2)
except shutil.Error as e:
messagebox.showerror("Error", "Failed to move file: " + os.path.basename(file) + " to " + pathto + "\\" + date + "\\" + os.path.basename(file) + "newline newline" + str(e))
errors += 1
# Update progress bar
sortProgress["value"] += progressInterval
sortProgress.update()
else:
errors += 1
sortProgress["value"] += progressInterval
sortProgress.update()
# Reset sort to path entry
ttk.Label(sortFrame, text="Sort to: ").grid(column=0, row=0, sticky=W)
sortPath = ttk.Entry(sortFrame, width=50)
sortPath.grid(column=1, row=0, sticky=(W, E))
#create finished dialog window
doneWindow = Toplevel(app)
doneWindow.title("Done!")
doneFrame = ttk.Frame(doneWindow, padding="3 3 12 12")
doneFrame.grid(column=3, row=0, sticky=(N, W, E, S))
doneWindow.columnconfigure(0, weight=1)
doneWindow.rowconfigure(0, weight=1)
ttk.Label(doneFrame, text="Sorting Complete! Sorted " + str(len(files)- errors) + " files.").grid(column=0, row=1, sticky=W)
ttk.Button(doneFrame, text="Close", command=doneWindow.destroy).grid(column=0, row=3, sticky=E)
def sortByName():
pass
# Run tkinter window
app.mainloop()