Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoLab Accessing Files

It is great that I can run jupyter notebooks in CoLab, but I am going crazy saving and loading files. For example, I am writing an assignment for my course and I include figures in it using the HTML tag. (I want to use HTML instead of markdown images so I can set the width.) So in a Text cell I have

<img src="CoLab04.png" width="250">

This works fine when I run the jupyter notebook on my laptop, but in CoLab, it can't find the image even when the image is in the same CoLab folder as the ipynb file. Err.

I have similar problems saving data files. On my laptop I can use the normal python functions open, write, close, etc. That code runs without complaint, but the files do not show up on Google Drive. Not in the CoLab folder or any other folder when I search all of my Google Drive. Err. I read TFM and use

from google.colab import drive, files
drive.mount('/content/gdrive')
fig.savefig("LED12.png") # saves a figure as a file
files.download("LED12.png")

This downloads a file to my laptop. Then I have to upload the file to a Google Drive folder so my students can see it.

Am I missing something? Why is it so hard to create and read Google Drive files using a Google-CoLab jupyter notebook?

I've read https://colab.research.google.com/notebooks/io.ipynb, but why is it so hard? I need something easy for novice students to use. If reading and writing files is this hard, I will have to recommend my students install jupyter on their laptops and not use CoLab.

like image 342
Prof Huster Avatar asked Oct 28 '25 03:10

Prof Huster


1 Answers

It seems to me a sys.path problem.

After you mount My Drive by the following code

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

then your main Google Drive can be read with

!ls /content/drive/My Drive/

If you have a sub-folder under My Drive that you wish to centralize your colab project, let's say you have projectA folder under your main Google Drive directory. You can add the projectA folder path to sys.path

import sys
sys.path.append("/content/drive/My Drive/projectA")

Then you should be able to save your fig as the same way you used in your local machine root path. The file will be save to your projectA folder where you run your colab code.

fig.savefig("LED12.png")

You should be able to see the file appear there. If this doesn't work, then try using absolute path when doing open, save, close etc. path sensitive operation:

working_path = '/content/drive/My Drive/projectA'
fig.savefig(os.path.join(working_path, "LED12.png"))
like image 134
Katherine Chen Avatar answered Oct 29 '25 15:10

Katherine Chen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!