Search code examples
pythonjupyter-notebooknbconvert

How can I save .py text version of jupyter notebook from the notebook itself


I want to save a text version (.py) of a Jupyter notebook (.ipynb) without output for version control purposes.

I know you can do this by running jupyter nbconvert in terminal, but how can I automate this by executing this command from within the Jupyter notebook itself?

Also see Using IPython / Jupyter Notebooks Under Version Control


Solution

  • You can save a text version (.py) of the notebook by adding this cell at the top of your Jupyter notebook. The Python file will be saved in the same folder. You can specify --output-dir if you like.

    import os
    
    nb_name = "mynotebook1.ipynb" #TODO change this to the file name of your Jupyter notebook
    
    basename, ext = os.path.splitext(nb_name)
    input_path = os.path.join(os.getcwd(), nb_name)
    
    !jupyter nbconvert "{input_path}" --to="python" --output="{basename}"
    

    According to this, the following also work with 2 cells

    First cell

    %%javascript
    IPython.notebook.kernel.execute('nb_name = "' + IPython.notebook.notebook_name + '"')
    

    Second cell

    import os
    
    basename, ext = os.path.splitext(nb_name)
    input_path = os.path.join(os.getcwd(), nb_name)
    
    !jupyter nbconvert "{input_path}" --to="python" --output="{basename}"
    

    If you use this tool, you can make it with just one cell https://pypi.org/project/ipynbname/

    import ipynbname
    import os
    
    nb_name= ipynbname.name()
    
    basename, ext = os.path.splitext(nb_name)
    input_path = os.path.join(os.getcwd(), nb_name)
    
    !jupyter nbconvert "{input_path}" --to="python" --output="{basename}"