pythonfile-uploadjupyter-notebookgoogle-colaboratory

User input to upload files to Google Drive via Google Colab Notebook


I'm designing a tool that is going to be used by lots of non-coders, and the easiest way to have it accessible to everyone is through a notebook on Google Colab. Within the notebook, I'd like to be able to prompt for user input, e.g. "upload a video folder" and have this be uploaded to a specific folder within google drive. That way, the notebook can access this folder throughout the program without users having to manually specify any filepaths. Does anyone know of a way to do this?

I have read a similar post which suggested:

from google.colab import files

files.upload()

but this only uploads to the notebook's limited temporary storage and not the user's Google Drive. Folders being uploaded may be around 1 to 2gb (containing dozens of .avi videos).


Solution

  • I don't know if this resolves all your problems but Google Colab has special module to access Google Drive

    from google.colab import drive
    
    drive.mount('/content/drive')
    

    and it will display drive/MyDrive in Files on right side.

    enter image description here

    And Google Colab allows to set target folder in upload()

    from google.colab import files
    
    files.upload('/content/drive/MyDrive')
    #files.upload('drive/MyDrive')
    

    You can access this drive in code

    import os
    
    os.listdir('/content/drive/MyDrive')
    
    import pandas
    
    df = pd.read_csv('/content/drive/MyDrive/my_data.csv')
    

    Google Colab doc: External data: Local Files, Drive, Sheets, and Cloud Storage - Colab


    You can use ipython.widgets (like Dropdown or Select) to display list of folders and execute upload with selected folder.

    import ipywidgets as widgets
    from IPython.display import display
    
    base = '/content/drive/MyDrive'
    
    filenames = os.listdir(base)
    folders = [name for name in filenames if os.path.isdir(os.path.join(base, name))]
    
    # add base folder on drive as first on list
    folders.insert(0, '.')
    
    Dropdown_ = widgets.Dropdown(
        options=folders,
        description='Select folder',
    )
    
    output = widgets.Output()
    
    def on_change(change):
        name = change['new']
        fullname = os.path.join(base, name)
        print('name:', name)
        print('full:', fullname)
        files.upload(fullname)
    
    Dropdown_.observe(on_change, names='value')
    display(Dropdown_)
    

    (based on code from answer: python - Using google colab forms input as dropdown, can I put the read file and add on the total list? - Stack Overflow)

    IPython doc: dropdown, select, file-upload