Advertisement
SuperSonicBlast

File rename

Feb 11th, 2024
845
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. import os
  2. import time
  3. from watchdog.observers import Observer
  4. from watchdog.events import FileSystemEventHandler
  5.  
  6. class NewFileHandler(FileSystemEventHandler):
  7.     def on_created(self, event):
  8.         if not event.is_directory:
  9.             file_path = event.src_path
  10.             if os.path.isfile(file_path):
  11.                 self.rename_file(file_path)
  12.  
  13.     def rename_file(self, file_path):
  14.         timestamp = os.path.getmtime(file_path)
  15.         formatted_timestamp = time.strftime("%Y%m%d-%H%M%S", time.localtime(timestamp))
  16.         new_filename = f"{formatted_timestamp}.png"
  17.         directory = os.path.dirname(file_path)
  18.         new_file_path = os.path.join(directory, new_filename)
  19.        
  20.         # Wait for the file to be released before attempting to rename it
  21.         max_retries = 5
  22.         retries = 0
  23.         while retries < max_retries:
  24.             try:
  25.                 os.rename(file_path, new_file_path)
  26.                 print(f"Renamed '{os.path.basename(file_path)}' to '{new_filename}'")
  27.                 break
  28.             except OSError as e:
  29.                 print(f"Error renaming file: {e}")
  30.                 print("Retrying...")
  31.                 retries += 1
  32.                 time.sleep(1)
  33.         else:
  34.             print(f"Failed to rename '{os.path.basename(file_path)}' after {max_retries} retries.")
  35.  
  36. if __name__ == "__main__":
  37.     folder_to_watch = "D:\screenshots"
  38.     event_handler = NewFileHandler()
  39.     observer = Observer()
  40.     observer.schedule(event_handler, folder_to_watch, recursive=False)
  41.     observer.start()
  42.     print(f"Watching '{folder_to_watch}' for new files...")
  43.     try:
  44.         while True:
  45.             time.sleep(1)
  46.     except KeyboardInterrupt:
  47.         observer.stop()
  48.         observer.join()
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement