0

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 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

and what about colab notebook?
@dtr43 should work as well.
2

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

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?
What is the error?
The error is : JSON.parse: unexpected character at line 1 column 1 of the JSON data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.