Get a shareable link of a file in our google drive using Colab notebook

浪子不回头ぞ 提交于 2020-05-12 08:22:20

问题


could anyone please inform me how to automatically get a shareable link of a file in our google drive using Colab notebook?

Thank you.


回答1:


You can use xattr to get file_id

from subprocess import getoutput
from IPython.display import HTML
from google.colab import drive
drive.mount('/content/drive')  # access drive
# need to install xattr
!apt-get install xattr > /dev/null
# get the id
fid = getoutput("xattr -p 'user.drive.id' '/content/drive/My Drive/Colab Notebooks/R.ipynb' ")
# make a link and display it
HTML(f"<a href=https://colab.research.google.com/drive/{fid} target=_blank>notebook</a>")

Here I access my notebook file at /Colab Notebooks/R.ipynb and make a link to open it in Colab.




回答2:


If you look into the documentation you can see a section that explain how to list files from Drive.

Using that and reading the documentation of the library used, I've created this script:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials

auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)

files = drive.ListFile().GetList()
for file in files:
  keys = file.keys()
  if 'webContentLink' in keys:
    link = file['webContentLink']
  elif 'webViewLink' in keys:
    link = file['webViewLink']
  else:
    link = 'No Link Available. Check your sharing settings.'

  if 'name' in keys:
    name = file['name']
  else:
    name = file['id']

  print('name: {}  link: {}'.format(name, link))

This is currently listing all files and providing a link to it.

You can then edit the function to find a specific file instead.

Hope this helps!



来源:https://stackoverflow.com/questions/58958149/get-a-shareable-link-of-a-file-in-our-google-drive-using-colab-notebook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!