Skip to content

Instantly share code, notes, and snippets.

@sdelquin
Created May 15, 2018 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdelquin/31b4605c01d0a6cfeb6fd4610adc9643 to your computer and use it in GitHub Desktop.
Save sdelquin/31b4605c01d0a6cfeb6fd4610adc9643 to your computer and use it in GitHub Desktop.
Watch a directory and rename created files with a timestamp
# pip install watchdog
# python3 rename.py <path>
import sys
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import datetime
import os
FILE_FORMAT = "%Y%m%d_%H%M%S%f"
class FileRenamer(FileSystemEventHandler):
def on_created(self, event):
path = event.src_path
now = datetime.datetime.now().strftime(FILE_FORMAT)
head, tail = os.path.split(path)
_, ext = os.path.splitext(tail)
new_path = os.path.join(head, f"{now}{ext}")
print(f"Renaming {path} --> {new_path}")
os.rename(path, new_path)
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else '.'
event_handler = FileRenamer()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment