tetedp
tetedp

Reputation: 1693

Upload File From Colab to Google Drive Folder

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.

Upvotes: 6

Views: 17793

Answers (4)

Erhan Tiryaki
Erhan Tiryaki

Reputation: 1

from google.colab import drive
from google.colab import files
import shutil
import os

# 1. Mount Google Drive
drive.mount('/content/drive')

# 2. Upload the file
uploaded = files.upload()

# 3. Get the filename
filename = list(uploaded.keys())[0]

# 4. Specify the destination path
destination_path = os.path.join('/content/drive/My Drive/Your_Folder', filename)  # Replace 'Your_Folder' with your desired folder name

# 5. Move the uploaded file to the destination
shutil.move(filename, destination_path) 

print(f'File "{filename}" uploaded to "{destination_path}" successfully.')

Upvotes: 0

Aayush Anand
Aayush Anand

Reputation: 55

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

Upvotes: 0

SHAMI
SHAMI

Reputation: 51

**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")

Upvotes: 5

korakot
korakot

Reputation: 40928

I take from this answer

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

Upvotes: 2

Related Questions