-
Notifications
You must be signed in to change notification settings - Fork 0
/
file-sorter.py
60 lines (49 loc) · 1.99 KB
/
file-sorter.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
import os
from time import sleep
from shutil import move
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
src_folder = os.path.join(os.path.expanduser('~'), 'Downloads/Documents')
dest_folder = os.path.join(os.path.expanduser('~'), 'Downloads')
#Destination folder validation
if not os.path.exists(dest_folder):
os.makedirs(dest_folder)
print(f"Destination folder {dest_folder} created.")
class DocumentMoverHandler(FileSystemEventHandler):
def move_existing_files(self):
for entry in os.scandir(src_folder):
if entry.is_file() and entry.name.endswith((".doc", ".docx", ".pdf")):
#move(entry.path, dest_folder)
self.move_file(entry)
print(f"Moved {entry.name} to {dest_folder}")
def on_created(self, event):
self.move_all_files()
def on_modified(self, event):
self.move_all_files()
def move_all_files(self):
for entry in os.scandir(src_folder):
if entry.is_file() and entry.name.endswith((".doc", ".docx", ".pdf")):
#move(entry.path, dest_folder)
self.move_file(entry)
print(f"Moved {entry.name} to {dest_folder}")
def move_file(self, entry):
# Check if the source and destination folders are different
if entry.path != dest_folder:
try:
move(entry.path, os.path.join(dest_folder, entry.name))
print(f"Moved {entry.name} to {dest_folder}")
except Exception as e:
print(f"Error moving {entry.name}: {e}")
if __name__ == "__main__":
event_handler = DocumentMoverHandler()
# Move existing files immediately upon starting the script
event_handler.move_existing_files()
observer = Observer()
observer.schedule(event_handler, src_folder, recursive=True)
observer.start()
try:
while True:
sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()