Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to convert .ipynb to .py in VSCode

I'm looking for a good way to convert .ipynb to .py files in VSCode. So far I've tried:

  • the "Export As" Option built into vscode. Not ideal as it produces the following at the start of the script, as well as "Run Cell", "Run Below", etc. buttons/links:

"To add a new cell, type '# %%' To add a new markdown cell, type '# %% [markdown]' %% from IPython import get_ipython"

  • nbconvert. I usually insert this as a command in the script itself (https://stackoverflow.com/a/19779226/14198216) so it's automatically converted and saved once run. But this also leaves "Run Cell" etc, as well as execution markings (ex: "In [1]")

  • jupytext. I also usually insert this as a command. At the start of the .py, it produces:

-- coding: utf-8 -- --- jupyter: jupytext: text_representation:

Is there a nice, minimalist solution that doesn't insert a bunch of gunk (which needs to be manually edited out) in the .py version of my notebooks and can be easily/automatically executed from the notebook itself? This could also be setting tweaks that I'm currently unaware of that can make one of the things I mentioned work better.

Thanks in advance.

like image 914
Isaac Liu Avatar asked Sep 11 '25 12:09

Isaac Liu


2 Answers

You need to install the Jupyter package:

https://marketplace.visualstudio.com/items?itemName=ms-toolsai.jupyter

Then open "Command Palette" (⇧⌘P) and search for this line:
Jupyter: Convert/Export to Python script \

enter image description here

like image 177
Mohamad Hamouday Avatar answered Sep 13 '25 02:09

Mohamad Hamouday


In VSCode v1.75.1, if you right-click on a notebook file (.ipynb) in the file explorer side panel, you will have an option called 'Import Notebook to Script'. This worked for me. Image shows options after right-click

like image 30
stormchaser68 Avatar answered Sep 13 '25 00:09

stormchaser68