Created
May 15, 2018 17:15
-
-
Save sdelquin/31b4605c01d0a6cfeb6fd4610adc9643 to your computer and use it in GitHub Desktop.
Watch a directory and rename created files with a timestamp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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