Skip to content

Instantly share code, notes, and snippets.

@jmclong
Created August 26, 2021 19:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmclong/6ae478023914874041a1eb3e434dd5e2 to your computer and use it in GitHub Desktop.
Save jmclong/6ae478023914874041a1eb3e434dd5e2 to your computer and use it in GitHub Desktop.
Save a copy of a Jupyter notebook in a '.history' folder every time the notebook is saved
import os
import shutil
import pathlib
from datetime import datetime
def post_save(model, os_path, contents_manager):
"""post-save hook for saving backups of jupyter files."""
if model['type'] != 'notebook':
return # only do this for notebooks
directory, filename = os.path.split(os_path)
history_directory = pathlib.Path(directory, '.history')
if not history_directory.exists():
history_directory.mkdir()
now = datetime.now()
shutil.copy2(os_path, history_directory.joinpath(now.strftime("%d_%m_%Y_%H_%M_%S") + filename))
c.FileContentsManager.post_save_hook = post_save
@jmclong
Copy link
Author

jmclong commented Aug 26, 2021

Execute jupyter notebook --generate-config and add this snippet at the bottom of the generated config. Restart Jupyter and it should work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment