Links

Count code lines

Tags: #jupyternotebooks #naas #jupyter-notebooks #read #codelines #snippet #operations #text
Author: Florent Ravenel
Description: This notebook provides a tool to count the number of lines of code in a Jupyter Notebook.

Input

Import libraries

import json

Variables

# Input
notebook_path = "../template.ipynb"

Model

Get module libraries in notebook

def count_codes(notebook_path):
with open(notebook_path) as f:
nb = json.load(f)
data = 0
cells = nb.get("cells")
# Check each cells
for cell in cells:
cell_type = cell.get("cell_type")
sources = cell.get("source")
for source in sources:
if cell_type == "code":
if not source.startswith("\n") and not source.startswith("#"):
data += 1
if data == 0:
print("❎ No line of code wrote in notebook:", notebook_path)
else:
print(f"✅ {data} line(s) of code wrote in notebook:", notebook_path)
return data

Output

Display result

no_lines = count_codes(notebook_path)
no_lines