将JSON对象另存为Jupyter ipynb文件

时间:2018-06-21 10:21:33

标签: python json jupyter

我已经将Jupyter笔记本文件(ipynb)读入Jupyter作为json对象以进行清理:

import json
with open('C:/Python/Scripts/MyNotebook.ipynb') as json_file:  
    jsonin= json.load(json_file)

然后我删除一些没有指定字符串#keepthis的代码块:

jsonout=jsonin
if '#keepthis' not in str(jsonout['cells'][1]['source']):
    jsonout['cells'][1] = np.nan

这很好。现在如何将jsonout转换回.ipynb文件?我已经尝试过了:

!jupyter nbconvert --to jsonout 'C:/Python/Scripts/MyNotebookClean.ipynb'

但是,尽管我在与原始MyNotebookClean.ipynb文件相同的位置上手动创建MyNotebook.ipynb文件:[NbConvertApp] WARNING | pattern "'C:/Python/Scripts/MyNotebookClean.ipynb'" matched no files

,但仍然收到此错误

1 个答案:

答案 0 :(得分:0)

我找到了将json对象写回ipynb文件的答案。很简单:

with open('C:/Python/Scripts/MyNotebookClean.ipynb', 'w') as outfile:
    json.dump(jsonout, outfile)

此外,我应该使用del jsonout['cells'][1]而不是jsonout['cells'][1] = np.nan