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

rchurt
  • 1,395
  • 1
  • 10
  • 21

3 Answers3

3

I think you can use the below command:

%cd [your path]
Matteo Zanoni
  • 3,429
  • 9
  • 27
Mohsen Navazani
  • 131
  • 1
  • 6
1

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.

Laurent
  • 12,287
  • 7
  • 21
  • 37
Slayt3r
  • 11
  • 2
1

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.

Shubham
  • 1,310
  • 4
  • 13