Search code examples
pythongoogle-colaboratory

How to upload a specific file to Google Colab?


I have a file on my computer that I want to upload to Google Colab. I know there are numerous ways to do this, including a

from google.colab import files
uploaded = files.upload()

or just uploading manually from the file system. But I want to upload that specific file without needing to choose that file myself. Something like:

from google.colab import files
file_path = 'path/to/the/file'
files.upload(file_path)

Is there any way to do this?


Solution

  • Providing a file path directly rather than clicking through the GUI for an upload requires access to your local machine's file system. However, when your run cell IPython magic commands such as %pwd in Google collab, you'll notice that the current working directory shown is that of the notebook environment - not that of your machine. The way to eschew the issue are as follows.

    1. Local Runtime

    Only local runtimes via Jupyter seems to enable such access to the local file system. This necessitates the installation of jupyterlab, a Jupyter server extension for using a WebSocket, and launching a local server. See this tutorial.

    2. Google Drive

    In case Google Drive is convenient, you can upload files into Google Drive from your local machine without clicking through a GUI.

    3. Embracing the GUI

    If these options seem overkill, you, unfortunately, have to stick with

    from google.colab import files
    uploaded = files.upload()
    

    as you alluded to.