Skip to content

Instantly share code, notes, and snippets.

@kei0425 kei0425/ipynbconvert.py
Last active Mar 8, 2018

Embed
What would you like to do?
#<api>
import json
import os.path
cell_type_header = '#### cell_type: '
ipynb_json_header = '#### ipynb_json: '
def save_py(input_path, output_path=None):
if output_path is None:
filename, ext = os.path.splitext(input_path)
output_path = filename + '.py'
with open(input_path) as f:
data = json.load(f)
with open(output_path, 'w') as f:
for c in data['cells']:
f.write('{}{}\n'.format(cell_type_header, c['cell_type']))
if c['cell_type'] != 'code':
f.write('"""\n')
f.write(''.join(c['source']))
f.write('\n')
if c['cell_type'] != 'code':
f.write('"""\n')
f.write('{}{}\n'.format(ipynb_json_header, json.dumps({k:v for k,v in data.items() if k != 'cells'})))
return output_path
def load_py(input_path, output_path=None):
if output_path is None:
filename, ext = os.path.splitext(input_path)
output_path = filename + '.ipynb'
cells = []
source = None
cell_type = None
with open(input_path) as f:
for line in f:
if line.startswith(ipynb_json_header):
data = json.loads(line[len(ipynb_json_header):])
elif line.startswith(cell_type_header):
cell_type = line[len(cell_type_header):-1]
source = []
cell = dict(cell_type=cell_type, metadata={}, source=source)
cells.append(cell)
elif source is not None:
source.append(line)
for cell in cells:
if cell['cell_type'] == 'code':
# codeは情報を付与
cell['outputs'] = []
cell['execution_count'] = None
else:
# 先頭と最後に"""が入っているので削除
cell['source'] = cell['source'][1:-1]
# 最後の改行を削除
cell['source'][-1] = cell['source'][-1][:-1]
data['cells'] = cells
with open(output_path, 'w') as f:
json.dump(data, f, indent=2)
return output_path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.