Get a shareable link of a file in our google drive

2020-07-27 03:55发布

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

Thank you.

2条回答
欢心
2楼-- · 2020-07-27 04:29

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.

查看更多
劳资没心,怎么记你
3楼-- · 2020-07-27 04:33

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!

查看更多
登录 后发表回答