简体   繁体   中英

Relative path in Google Drive mounted in Google Colab

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

I think you can use the below command:

%cd [your path]

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.

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 %cd ing into after mounting their drives.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM