1

I want to save the Jupyter Notebooks as a .py script but when I do it still keeps the cell notation, for example # In[81].

The problem is VS Code still recognizes this as a cell, so I can't run it like a script. How do I save the notebooks as a script but without the cell notations?

I've already tried:

  1. file -> download as -> Python(.py)
  2. Using nbconvert - I get the same result

In command I tried nbconvert:

jupyter nbconvert --to python example.ipynb

I still get a .py script with cells.

  • This probably isn't the best approach, but you could just merge your cells and then copy + paste into a clean .py file. – Amir Almusawi Jul 18 '19 at 20:35
  • If you download it as (.py) it adds the cell notations as comments (with '#'). So you can run it as a script using the terminal. I don't know vscode, but it shouldn't change its bahaviour based on comments. Maybe there is an option to change vscode's behaviour in the configurations? – klaus Jul 18 '19 at 20:43
  • 1
    [Jupytext](https://jupytext.readthedocs.io/en/latest/index.html) allows setting `cell_markers`, see that term on [this page](https://jupytext.readthedocs.io/en/latest/formats.html#the-percent-format) to get a sense. As it has a lot of power, exemplified [here](https://jupytext.readthedocs.io/en/latest/using-cli.html) it is a good tool to have in your toolbox for working with notebooks. Also nbformat is good to know about because you can customize your own parsing of a notebook because it has the concepts and abstractions of notebooks baked in, see https://stackoverflow.com/a/74379308/8508004. – Wayne Jun 01 '23 at 12:29

1 Answers1

2

You could write a short python script to parse out the cell notation blocks and substitute them for empty strings. For example:

import re #python regular expression matching module
with open('downloaded_py_file.py', 'r') as f_orig:
    script = re.sub(r'# In\[.*\]:\n','', f_orig.read())
with open('out_file.py','w') as fh:
    fh.write(script)

Still download the file as a .py file first. This code will save the file as a script without the cell notation blocks.

Hope this helps!

L0tad
  • 574
  • 3
  • 15
zsheryl
  • 73
  • 7