Count code lines
Tags: #naas #jupyter-notebooks #read #codelines #snippet
Author: Florent Ravenel

Input

Import libraries

1
import json
Copied!

Variables

1
# Input
2
notebook_path = "../template.ipynb"
Copied!

Model

Get module libraries in notebook

1
def count_codes(notebook_path):
2
with open(notebook_path) as f:
3
nb = json.load(f)
4
data = 0
5
6
cells = nb.get("cells")
7
# Check each cells
8
for cell in cells:
9
cell_type = cell.get('cell_type')
10
sources = cell.get('source')
11
for source in sources:
12
if cell_type == "code":
13
if not source.startswith('\n') and not source.startswith('#'):
14
data += 1
15
if data == 0:
16
print("❎ No line of code wrote in notebook:", notebook_path)
17
else:
18
print(f"✅ {data} line(s) of code wrote in notebook:", notebook_path)
19
return data
Copied!

Output

Display result

1
no_lines = count_codes(notebook_path)
2
no_lines
Copied!
1
Copied!
Copy link
Edit on GitHub