How To Write Text In Jupyter Notebook And IPython To File

IPython provides a lot of magic commands, with the %%writefile command, you can create a text file and write text in jupyter notebook to the file in the IPython interface easily. This article will show you two examples to demo how to open a file in jupyter notebook and how to write text in jupyter notebook to a file.

1. How To Write Text To File In Ipython.

  1. Open a terminal and input ipython command.
  2. Then write the below source code in the ipython interactive console. You can input multiple line text, to end input text and write text to file click Esc key and then click Enter key. Then ipython will write all your input line text into the file. If the target file exists, then the file content will be overridden.
    $ ipython
    Python 3.7.1 (default, Dec 14 2018, 19:28:38) 
    Type 'copyright', 'credits' or 'license' for more information
    IPython 7.2.0 -- An enhanced Interactive Python. Type '?' for help.
    
    In [1]: %%writefile abc.txt 
       ...: hello ipython, this is the first text file. 
       ...:                                                                                                                                                                                                     
    Writing abc.txt
    
    In [2]: %%writefile abc.txt 
       ...: hello ipython world 
       ...: this is from command line 
       ...: i love ipython 
       ...:                                                                                                                                                                                                     
    Overwriting abc.txt
    
  3. Run the below command to check the text file content.
    In [3]: ls -l  # this command make sure abc.txt file has been created.                                                                                                                                                                                           
    total 72
    -rw-r--r--  1 zhaosong zhaosong   61 3月  19 10:01 abc.txt
    drwxr-xr-x 24 zhaosong zhaosong 4096 3月   3 20:37 anaconda3/
    drwxr-xr-x  3 zhaosong zhaosong 4096 12月  2 20:13 Android/
    drwxr-xr-x  2 zhaosong zhaosong 4096 12月 20 20:38 Desktop/
    drwxr-xr-x  3 zhaosong zhaosong 4096 11月 16 14:31 Documents/
    drwxr-xr-x  3 zhaosong zhaosong 4096 3月   7 10:07 Downloads/
    drwxrwxr-x  3 zhaosong zhaosong 4096 12月 16 20:40 eclipse/
    drwxrwxr-x  3 zhaosong zhaosong 4096 12月 16 20:49 eclipse-workspace/
    -rw-r--r--  1 zhaosong zhaosong 8980 11月 16 12:08 examples.desktop
    drwxr-xr-x  2 zhaosong zhaosong 4096 11月 16 12:30 Music/
    drwxr-xr-x  2 zhaosong zhaosong 4096 3月  18 21:17 Pictures/
    drwxr-xr-x  2 zhaosong zhaosong 4096 11月 16 12:30 Public/
    drwxr-xr-x  3 zhaosong zhaosong 4096 1月  21 12:50 snap/
    drwxr-xr-x  2 zhaosong zhaosong 4096 11月 16 12:30 Templates/
    drwxr-xr-x  2 zhaosong zhaosong 4096 3月   4 10:44 Videos/
    drwxr-xr-x  4 zhaosong zhaosong 4096 1月   8 11:57 WorkSpace/
    
    # open abc.txt with read permission.
    In [4]: file = open('./abc.txt','r')                                                                                                                                                                        
    
    # print abc.txt file content
    In [5]: print(file.read())                                                                                                                                                                                  
    hello ipython world
    this is from command line
    i love ipython
    
  4. Run exit() function to exit ipython interface.
    In [6]: exit()                                                                                                                                                                                              
    zhaosong@zhaosong-VirtualBox:~$

2. How To Write Text In Jupyter Notebook To File And Open The File To Read File Content.

  1. Run the $ jupyter notebook command to start jupyter web server.
    $ jupyter notebook
    [I 10:10:48.377 NotebookApp] The port 8888 is already in use, trying another port.
    [I 10:10:48.606 NotebookApp] JupyterLab extension loaded from /home/zhaosong/anaconda3/lib/python3.7/site-packages/jupyterlab
    [I 10:10:48.606 NotebookApp] JupyterLab application directory is /home/zhaosong/anaconda3/share/jupyter/lab
    [I 10:10:48.607 NotebookApp] Serving notebooks from local directory: /home/zhaosong
    [I 10:10:48.607 NotebookApp] The Jupyter Notebook is running at:
    [I 10:10:48.607 NotebookApp] http://localhost:8889/?token=5ac4d4ff2c59bafd77f5c82bdf4c56199497792f499b8e29
    [I 10:10:48.607 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
    [C 10:10:48.703 NotebookApp] 
        
        To access the notebook, open this file in a browser:
            file:///run/user/1000/jupyter/nbserver-8327-open.html
        Or copy and paste one of these URLs:
            http://localhost:8889/?token=5ac4d4ff2c59bafd77f5c82bdf4c56199497792f499b8e29
    [W 10:11:02.460 NotebookApp] delete /abc.txt
    
  2. Click the above URL to open the Jupyter notebook web GUI interface. The URL should contain the token value.
  3. Click New —> Python 3 menu item to create a new Jupyter notebook file (.ipynb file).
    run-python-2-and-python-3-code-in-jupyter-notebook-web-server
  4. Input below ipython code in the first cell line, then click the Run button to run it to create file abc.txt and write text data to it.
    %%writefile abc.txt
    hello world
    i love ipython
    jupyter notebook is so wonderful
  5. Input below ipython code in the second cell line, click Run button to read abc.txt file content out.
    with open('abc.txt', 'r') as f:
        print(f.read())
  6. Run the below ipython code in the third cell line to list the created abc.txt file.
    ls -l
  7. Below is the web page picture about the above actions.
    jupyter-notebook-write-text-to-file-web-ui
  8. Let us look at the terminal console, you can see the below output log data of the above process.
    Creating new notebook in 
    [I 10:14:24.947 NotebookApp] Kernel started: 767dc231-42a9-470f-8a07-f8c9e5621e9f
    [I 10:14:25.620 NotebookApp] Adapting to protocol v5.1 for kernel 767dc231-42a9-470f-8a07-f8c9e5621e9f
    [I 10:16:25.339 NotebookApp] Saving file at /Untitled.ipynb
    [I 10:18:36.869 NotebookApp] 302 GET /?token=5ac4d4ff2c59bafd77f5c82bdf4c56199497792f499b8e29 (127.0.0.1) 0.51ms
    [I 10:18:40.677 NotebookApp] Adapting to protocol v5.1 for kernel 767dc231-42a9-470f-8a07-f8c9e5621e9f
    [I 10:20:40.646 NotebookApp] Saving file at /Untitled.ipynb
    [I 10:22:40.651 NotebookApp] Saving file at /Untitled.ipyn

3. Q & A.

3.1 How To Write Jupyter Notebook Cell Content To A .ipynb File Programmatically In A Python Script.

This question is asked by Michael in the comments,  below is the answer wish it can help.

  1. The Jupyter notebook .ipynb file has JSON format content. The JSON file can contain both text, rich media text, program source code and metadata segment, one segment one cell.
  2. You can use the python nbformat library to implement the above goal. You can run the command pip install nbformat to install it first. If you want to programmatically create the Jupyter notebook file and write Jupython notebook content to the file you can refer to the below source code.
    # Import the python nbformat module
    import nbformat
    
    # Create a new jupyter notebook object.
    nb = nbformat.v4.new_notebook()
    
    # The text content that will be written into the jupyter notebook. 
    str = """ I love jupyter notebook and ipython"""
    
    # Create a new markdown cell object that contains the above string text.
    markdown_cell = nbformat.v4.new_markdown_cell(str)
    
    # Add the above markdown cell object into the jupyter notebook cells.
    nb['cells'] = [markdown_cell]
    
    # Invoke nbformat module's write method to write the above notebook object to a .ipynb file.
    nbformat.write(nb,'test.ipynb')
  3. The Python nbformat module’s GitHub website is https://github.com/jupyter/nbformat.

3 thoughts on “How To Write Text In Jupyter Notebook And IPython To File”

  1. I want to write ipython command into a Jupyter notebook file in python script code. I also want to write different type of Jupyter notebook cell content in the Jupyter notebook file use python script. But I found it difficult.

    I know I can create a .ipynb extension text file in python script use file = open(‘test.ipynb’, ‘w’) and then write the Jupyter notebook file content data into the test.ipynb file with the command file.write(‘print(\’Hello Jupyter.\’)’). But how to write other cell type content, is there any tools to do it?

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.