Last active
April 30, 2020 22:04
-
-
Save mvdoc/557151ad879e37611c35cc9dfb75b066 to your computer and use it in GitHub Desktop.
Jupyter notebook post hook save to rename untitled notebooks to `YYYY-MM-DD_untitled-N.ipynb`
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
# This file should be put in ~/.jupyter/ | |
# New notebooks will be renamed to YYYY-MM-DD_untitled-N.ipynb instead of Untitled.ipynb | |
# Please be aware that this code has **NOT** been tested extensively, I wrote it rather quickly, | |
# and thus your notebook might be deleted by accident. | |
# | |
# USE THIS CODE AT YOUR OWN RISK | |
# | |
import os | |
import re | |
import time | |
import shutil | |
time_template = '%Y-%m-%d' | |
date_re = re.compile(r"\d{4}-\d{2}-\d{2}") | |
def harmonize_filename(model, os_path, contents_manager, **kwargs): | |
# First check this is a notebook and it already starts with a date | |
if model['type'] != 'notebook' or date_re.search(os_path) is not None: | |
return | |
# make this work only for Untitled notebooks | |
# get notebook name | |
notebook_fn = os.path.basename(os_path) | |
if not notebook_fn.startswith('Untitled'): | |
return | |
# if not rename it as YYYY-MM-DD_current-notebook-name.ipynb | |
notebook_fn = notebook_fn.lower().replace(' ', '-') | |
today = time.strftime(time_template) | |
notebook_fn = f"{today}_{notebook_fn}" | |
# Now check if it already exist, as when we create new untitled notebooks | |
# if so, append a number | |
new_notebook = os.path.join(contents_manager.root_dir, notebook_fn) | |
while os.path.exists(new_notebook): | |
base, ext = os.path.splitext(notebook_fn) | |
# assumption: it will be titled YYYY-MM-DD_untitled-N.ipynb | |
try: | |
base_split = base.split('-') | |
number = int(base_split[-1]) | |
except ValueError: | |
number = 0 | |
number += 1 | |
if number == 1: | |
base_split.append(str(number)) | |
else: | |
base_split[-1] = str(number) | |
base = '-'.join(base_split) | |
notebook_fn = base + ext | |
new_notebook = os.path.join(contents_manager.root_dir, notebook_fn) | |
# change name in model too | |
model['name'] = notebook_fn | |
model['path'] = notebook_fn | |
# rename | |
old_notebook = os.path.join(contents_manager.root_dir, os_path) | |
shutil.move(old_notebook, new_notebook) | |
c.FileContentsManager.post_save_hook = harmonize_filename |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment