jupyter-notebookipythongoogle-colaboratory

Importing .py files in Google Colab


Is there any way to upload my code in .py files and import them in colab code cells?

The other way I found is to create a local Jupyter notebook then upload it to Colab, is it the only way?


Solution

  • You can save it first, then import it.

    from google.colab import files
    src = list(files.upload().values())[0]
    open('mylib.py','wb').write(src)
    import mylib
    

    Update (nov 2018): Now you can upload easily by

    Update (oct 2019): If you don't want to upload every time, you can store it in S3 and mount it to Colab, as shown in this gist

    Update (apr 2020): Now that you can mount your Google Drive automatically. It is easier to just copy it from Drive than upload it.