Relative path in Google Drive mounted in Google Colab
Asked Answered
F

3

12

I have a Google Colab notebook that I want to distribute to other users, and I want to include relative paths for files and directories in my mounted Google Drive so that the code doesn't break when they put it in a different directory than the one I have it in.

Specifically, in python cells, I'm hoping to be able to write a path like ./demo/output/genomes/gbks instead of the absolute path /gdrive/My Drive/Github/cluster_identification/demo/output/genomes/gbks(because the notebook itself is contained within /gdrive/My Drive/Github/cluster_identification).

I'm wondering if I can use sys.path.append somehow to add the notebook path to my python path, but I'm not sure how to do that in a way that doesn't require me to specify an absolute path there, and even if I'm able to add it, I'm not sure how to make use of it when trying to define paths in python cells.

I found this answer (Get the path of the notebook on Google Colab) which gave a clue, but it doesn't completely solve my problem, and also isn't a very robust solution because it will only work if the name of the notebook is unique in Google Drive.

Thanks in advance for the help!

-Rob

Forde answered 10/6, 2020 at 22:42 Comment(2)
Did you manage to do this?Maravedi
No, sadly I couldn't figure it outForde
S
2

Something like this could help: sys.path.insert(0,"/content/drive/MyDrive/.../...")

Then it should be easy to access the files from the specific directories.

Simmer answered 2/4, 2021 at 14:15 Comment(0)
C
2

I think you can use the below command:

%cd [your path]
Comical answered 1/6, 2021 at 18:3 Comment(0)
C
0

Just run this:

% cd /gdrive/My Drive/Github/cluster_identification

Then you can use paths like: ./demo/output/genomes/gbks

If you plan for multiple users to use the notebook, they will have to be careful to change the path they are %cding into after mounting their drives.

Cultivable answered 1/6, 2021 at 18:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.