Search code examples
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

    • click at [>] to open the left pane
    • choose file tab
    • click [upload] and choose your [mylib.py]
    • import mylib

    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.

    • Store mylib.py in your Drive
    • Open a new Colab
    • Open the (left)side pane, select Files view
    • Click Mount Drive then Connect to Google Drive
    • Copy it by !cp drive/MyDrive/mylib.py .
    • import mylib