6

I want to upload a file from colab to a specific folder in my google drive. I can get the folder by using the folder id and below snippet:

my_folder = drive.ListFile(
        {'q': "'1QYaM1vaUvdzbdsfWbsolncz1xc2pgnpextuP' in parents"}).GetList()

But my question: how do I upload a file(image) to this folder? Is there a function such as

my_folder.upload(my_file)?

So far I have seen some examples with zip files but I do not want to upload it as a zip file.

1
  • I would be interested to know how you can so it using a zip file. Commented Mar 4, 2023 at 3:56

3 Answers 3

5

**step(1) mount drive with colab **

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

step(2) import shutil

import shutil

step 3 copy file using shutil

shutil.copy("file_path","/content/drive/MyDrive/folder_name")
2

I take from this answer

fid = '1QYaM1vaUvdzbdsfWbsolncz1xc2pgnpextuP'
f = drive.CreateFile({"parents": [{"kind": "drive#fileLink", "id": fid}]})
f.SetContentFile( some_path )
f.Upload()
0

Even better solution is to just use the 'cp' GNU utility, in an empty cell of colab's notebook.

!cp sourceFileFolder/sourceFile.ext drive/MyDrive/DestFolderInGDrive/

Colabs run the Ubuntu OS and hence not only cp, but mv, zip, unzip, tar, bzip2, gzip are all available. git, gcc, g++, java, javac, python etc are available as well. For the google colab environment, once google drive is mounted, its just another folder in the local environment of colab.

For changing directories, you can use the magic command %cd path/to/directory/absolute/or/relative

Not the answer you're looking for? Browse other questions tagged or ask your own question.