Guest User

Untitled

a guest
May 20th, 2018
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. # pip install watchdog
  2. # python3 rename.py <path>
  3.  
  4. import sys
  5. import time
  6. from watchdog.observers import Observer
  7. from watchdog.events import FileSystemEventHandler
  8. import datetime
  9. import os
  10.  
  11.  
  12. FILE_FORMAT = "%Y%m%d_%H%M%S%f"
  13.  
  14.  
  15. class FileRenamer(FileSystemEventHandler):
  16. def on_created(self, event):
  17. path = event.src_path
  18. now = datetime.datetime.now().strftime(FILE_FORMAT)
  19. head, tail = os.path.split(path)
  20. _, ext = os.path.splitext(tail)
  21. new_path = os.path.join(head, f"{now}{ext}")
  22. print(f"Renaming {path} --> {new_path}")
  23. os.rename(path, new_path)
  24.  
  25.  
  26. if __name__ == "__main__":
  27. path = sys.argv[1] if len(sys.argv) > 1 else '.'
  28. event_handler = FileRenamer()
  29. observer = Observer()
  30. observer.schedule(event_handler, path, recursive=True)
  31. observer.start()
  32. try:
  33. while True:
  34. time.sleep(1)
  35. except KeyboardInterrupt:
  36. observer.stop()
  37. observer.join()
Add Comment
Please, Sign In to add comment