How do I upload a file into a specific folder in Google Colab?

Viewed 94

I want to upload a file into a specific folder using

from google.colab import files

uploaded = files.upload()

that codes only upload the file into one location, how can I make the uploaded files move into specific folder location automatically?

1 Answers

You can create folders and change directory to them using various Linux commands.

Firstly, in a single Colab cell, create a folder like this.

!mkdir -p /content/myfolder

The -p flag means it will work if the folder already exists and using /content/myfolder means it will create it in the correct place wherever it is run.

Then in another cell do this.

cd '/content/myfolder'

This changes to the new folder. It's important to make sure there are no lines above or below this line of code in the cell. You'll notice that there is no ! in front of the command. If you do use !, you will find that the change to the new directory is not remembered after the call.

Finally, do this in a third cell.

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

Edit:

It can be done in one cell if you use % in front of the cd command like so

!mkdir -p /content/myfolder
%cd /content/myfolder
from google.colab import files
uploaded = files.upload()
Related