How to edit and save text files (.py) in Google Colab? How to edit and save text files (.py) in Google Colab? python python

How to edit and save text files (.py) in Google Colab?


You can use Ipython magic commands. Use below command

%pycat code.py

A pop up will appear displaying the code. You can copy it and edit it locally.
Remove the file using below command

!rm code.py

Copy the edited code to a cell in notebook and add below command at the top of the cell

%%writefile code.py

Run the cell. A file will be created with the contents present in the cell.

Updates:Now there are lot more easy and convenient options.

  1. In the files section, there is an option to upload files or you can double click on the file, make changes and ctrl+s to save those changes.
  2. You can also use https://github.com/abhishekkrthakur/colabcode to edit using visual studio code server.


Colab includes a text editor you can use to create, open, and delete .py files directly.

All is done in the Files view (see below).

  • To create or delete a file, right click and choose "New file" or "Delete file".
  • To edit a file, double click on it. It appears on the right portion of your screen. Make any changes you wish. Changes are saved automatically.

enter image description here


Unfortunately, it seems, colab do not support %load line magic (yet), and yet, you can see the file content using !cat your_file.py and then manually, copy the output contents, write them to a new cell and write %%writefile your_new_file_name.py at the top of the new cell to save this back to the instance. Note that, this will not be saved to your google drive yet.

Example:!lsoutput: colabData/%%writefile something.pyprint("everything's fine.")!lsoutput: colabData/ something.py%run something.pyoutput: everything's fine.