Another approach of adding code from jupyter notebook cells to a .py is by using the built-in Magic command %logstart.
The %writefile saves the current cell code to a .py file.
%logstart
From the Documentation
Start logging anywhere in a session.
%logstart [-o|-r|-t|-q] [log_name [log_mode]]
If no name is given, it defaults to a file named ipython_log.py in your current directory, in rotate mode (see below).
%logstart name saves to file name in backup mode. It saves your history up to that point and then continues logging.
%logstart takes a second optional parameter: logging mode. This can be one of (note that the modes are given unquoted):
append
Keep logging at the end of any existing file.
backup
Rename any existing file to name~ and start name.
global
Append to a single logfile in your home directory.
over
Overwrite any existing log.
rotate
Create rotating logs: name.1~, name.2~, etc.
Check more options in the documentation
Example:
%logstop
%logstart -ort sample.py append
The above command appends all the Jupyter notebook code to sample.py
Note: Should run in the first cell