Cannot import .py file to ipython notebook

只谈情不闲聊 提交于 2019-11-29 11:19:27
user3273208

I had the same problem. This post helped: How to load/edit/run/save text files (.py) into an IPython notebook cell?

Basically, we just have to use the following command in the cell. And the .py file has to be in the same directory.

%load filename.py
alexis

I'm not sure why notebook doesn't support this natively, but I've concluded that the answer is: It can't be done from the command line or notebook GUI.

Control comments like <markdowncell> can only be interpreted by accessing notebook's API through python, as shown by @CliffordVienna in this answer to my related question.

import IPython.nbformat.current as nbf
nb = nbf.read(open('test.py', 'r'), 'py')
nbf.write(nb, open('test.ipynb', 'w'), 'ipynb')

Edit: The above method does not work with the current version (v4) of the Notebook API, so I have added this self-answer to show how it's done.

If you only need to import a local file, first use:

sys.path.append(os.getcwd())

to place the .pynb file's directory in sys.path, and then import the local file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!