'Convert raw Ipython Notebook txt to Ipynb

I have a textfile containing the source code for an Ipython Notebook.

How can I convert this file using Ipython / Python to an Ipython Notebook?

e.g. :

source.txt:

{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Test"
   ]
  },
}
...

The questions on SE deal with converting an actual notebook to a .py or otherwise. I'm looking just to get to the notebook in the first place.

Edit: I'm on Mac



Solution 1:[1]

You need to first install iPython package

pip install ipython

Save your current file as .py file using notepad++ Then try below code

import IPython.nbformat.current as convert
conv = convert.read(open('source.py', 'r'), 'py')
convert.write(conv, open('source.ipynb', 'w'), 'ipynb')

Solution 2:[2]

I found two ways to do, may this could help.

  1. Using Notepad: Open the file in Notepad. save notepad as name.ipynb instead of name.txt

    and make "save as type" All Files(.) instead of Text Documents (*.txt)

  2. Rename the file: Click File > Rename, change the name so that it ends with '.ipynb' behind, and click OK Close the file.

finally open file with your IDE or colab.

Solution 3:[3]

The latest implementation without warnings:

import nbformat

nb = nbformat.read('<file-path-with-format>', 
                   nbformat.current_nbformat)

nbformat.write(nb, '<path-to-save>/<filename>.ipynb', 
               nbformat.NO_CONVERT)

If nbformat is not installed install it like below

pip install nbformat

Read more about nbformat here.

Solution 4:[4]

I recently had the same issue. It took me a while to figure it out.

Copy all of the text in the file with the .txt extension

Open your Mac launchpad and search for TextEdit (I may have installed this)

Open TextEdit and create a new file

Paste the text in the new file and go to Save

enter image description here

When saving the file use the screenshot settings below to save as .ipynb file extension

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Pruthviraj Jadhav
Solution 3 Subhash Malireddy
Solution 4 Christopher