Links

Add tags in cells

Tags: #jupyternotebooks #jupyter #awesome-notebooks #tags #snippet #operations
Author: Florent Ravenel​

Input

Import library

import os
import json
from pprint import pprint

Setup your variables

# Notebook path to add tags
notebook_path = "AWS/AWS_Upload_file_to_S3_bucket.ipynb"
​
# Tags to added
new_tags = [f"awesome-notebooks/{notebook_path}"]

Model

Add tags in cells

def add_tags(notebook_path, new_tags):
with open(notebook_path) as f:
nb = json.load(f)
new_cells = []
cells = nb.get("cells")
# Apply change
for cell in cells:
tags = cell.get('metadata').get('tags')
if len(tags) == 0:
tags = new_tags
else:
tags += new_tags
cell["metadata"]["tags"] = tags
new_cells.append(cell)
# Save notebook
nb_new = nb.copy()
nb_new["cells"] = new_cells
with open(notebook_path, 'w') as f:
json.dump(nb_new, f)
print(f"✔️ {notebook_path} saved in Naas.")
return nb_new
​
nb = add_tags(notebook_path, new_tags)

Output

Display result

pprint(nb)