I am trying to create a project that will allow the user to automatically sort their files in the downloads folder based on keywords in the file name. Part of this program is allowing the user to choose their file name, so that it may be sorted correctly. I am having trouble getting the user to be able to name their file when prompted.
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import os
import json
import time
#Folders
folder_to_track = 'C:/Users/physi/Downloads'
image_destination = 'C:/Users/physi/Desktop/Images'
class MyHandler(FileSystemEventHandler):
i = 1
def on_modified(self, event):
for filename in os.listdir(folder_to_track):
time.sleep(5)
new_title = input("File Name: ")
extension = str(input("Extension: "))
new_name = folder_to_track + "/" + str(new_title + "." + extension)
os.rename(folder_to_track + "/" + filename, new_name)
time.sleep(2)
print("File Renamed!")
time.sleep(10)
src = folder_to_track + "/" + new_name
if 'Image' in new_name:
new_destination = image_destination + "/" + new_name
os.rename(src, new_destination)
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, folder_to_track, recursive=True)
observer.start()
try:
while True:
time.sleep(10)
except KeyboardInterrupt:
observer.stop()
observer.join()```
Above is the code that I have written, so far. When this code is run, it is able to detect when a new file is added to the Downloads folder, but as soon as it prompts the user to name their file, it prompts them with this error message...```
Traceback (most recent call last):
File "C:\Users\physi\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\physi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\watchdog\observers\api.py", line 203, in run
self.dispatch_events(self.event_queue, self.timeout)
File "C:\Users\physi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\watchdog\observers\api.py", line 376, in dispatch_events
handler.dispatch(event)
File "C:\Users\physi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\watchdog\events.py", line 331, in dispatch
{
File "C:\Users\physi\Desktop\File_Management.py", line 33, in on_modified
os.rename(filename, new_name)
FileNotFoundError: [WinError 2] The system cannot find the file specified: '37ea886b-25ed-4469-a13c-9c5fbf3ddd09.tmp' -> 'C:/Users/physi/Downloads/Hubble_Image..jfif'```
Could anyone help me to fix this program so it will allow the User to rename their file, then automatically save and sort it. Thanks, I appreciate the help!
This code was inspired by Kalle Hallden's Youtube Video