-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipynb2md.py
53 lines (44 loc) · 1.36 KB
/
ipynb2md.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import json
import os
from pathlib import Path
def readFile(fileName):
with open(fileName, "r", encoding="utf-8") as infile:
content = infile.read()
return content
def writeFile(fileName, data):
with open(fileName, "w", encoding="utf-8") as outfile:
outfile.write(data)
def concatNotebookCellSource(source: list):
data = ''
for line in source:
data += line
return data
def getCells(notebook: dict):
return notebook['cells']
def concatNotebookCells(cells: list):
data = ''
for cell in cells:
concatedSource = concatNotebookCellSource(cell['source'])
if cell['cell_type'] == 'code':
data += '```python\n'
data += concatedSource
data += '\n```'
else:
data += concatedSource
data += '\n'
return data
def getNotebookFiles():
ipynb_files = []
for dirpath, _, filenames in os.walk("."):
for file in filenames:
if file.endswith(".ipynb"):
ipynb_files.append(os.path.join(dirpath, file))
return ipynb_files
def changeExt(filePath, extName):
return f'{os.path.splitext(filePath)[0]}.{extName}'
files = getNotebookFiles()
for file in files:
notebookData = readFile(file)
cells = getCells(json.loads(notebookData))
data = concatNotebookCells(cells)
writeFile(changeExt(file, 'md'), data)