I want to explore and edit my .py files (python scripts) in the form of colab notebook. I already the uploaded my files in google drive and mounted in the environment. I can edit the file in the right pane but I want to open it as a notebook. I search the web but I couldn't find any solution for that. Is there any way to do so?
2 Answers
Let's say your file is script.py. You can use %%writefile script.py to edit your script.py inside the cell of jupyter notebook.
%writefile [-a] filename
Write the contents of the cell to a file.
The file will be overwritten unless the -a (--append) flag is specified.
positional arguments:
filename file to write
optional arguments:
-a, --append Append contents of the cell to an existing file. The file will
be created if it does not exist.
To read it, use !cat.
!cat script.py
You need to upload your code as a .ipynb in order for colab to open it as a notebook or create a new colaboratory in your drive and post your code to it
EDIT:
Alternatively you could create a Colaboratory and import your .py like this:
import importlib.util
spec = importlib.util.spec_from_file_location("test1.moduleName", "/content/drive/MyDrive/Colab Notebooks/test1.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.MyClass()
3 Comments
dtr43
Thank you for the solution. For the first suggestion, I exported my python script as .ipynb from spyder. but trying upload in colab. I got an error. What this problem may be?
RomanHDev
What is the error?
dtr43
The error is : JSON.parse: unexpected character at line 1 column 1 of the JSON data