A S*_*sh 4 google-colaboratory
我正在尝试从Google驱动器将文件下载到colaboratory。
file_id = '1uBtlaggVyWshwcyP6kEI-y_W3P8D26sz'
import io
from googleapiclient.http import MediaIoBaseDownload
request = drive_service.files().get_media(fileId=file_id)
downloaded = io.BytesIO()
downloader = MediaIoBaseDownload(downloaded, request)
done = False
while done is False:
# _ is a placeholder for a progress object that we ignore.
# (Our file is small, so we skip reporting progress.)
_, done = downloader.next_chunk()
downloaded.seek(0)
print('Downloaded file contents are: {}'.format(downloaded.read()))
Run Code Online (Sandbox Code Playgroud)
这样做会出现此错误:
NameError: name 'drive_service' is not defined
Run Code Online (Sandbox Code Playgroud)
如何清除此错误?
hop*_*per 45
无需安装/导入任何库。只需将您的文件 ID 放在最后。
!gdown --id yourFileIdHere
Run Code Online (Sandbox Code Playgroud)
注意:在撰写本文时,gdown 库已预装在 colab 上。
将文件从Google驱动器下载到colabo笔记本的最简单方法是通过colabo api:
from google.colab import drive
drive.mount('/content/gdrive')
!cp '/content/gdrive/My Drive/<file_path_on_google_drive>' <filename_in_colabo>
Run Code Online (Sandbox Code Playgroud)
备注:
小智 7
这是一个简单的方法。您可以使用 Python 中的 wget 命令或 requests 模块来完成工作。
# find the share link of the file/folder on Google Drive
file_share_link = "https://drive.google.com/open?id=0B_URf9ZWjAW7SC11Xzc4R2d0N2c"
# extract the ID of the file
file_id = file_share_link[file_share_link.find("=") + 1:]
# append the id to this REST command
file_download_link = "https://docs.google.com/uc?export=download&id=" + file_id
Run Code Online (Sandbox Code Playgroud)
file_download_link可以在浏览器地址栏中粘贴 in字符串,直接获取下载对话框。
如果使用 wget 命令:
!wget -O ebook.pdf --no-check-certificate "$file_download_link"
Run Code Online (Sandbox Code Playgroud)
步骤1
!pip install -U -q PyDrive
Run Code Online (Sandbox Code Playgroud)
第2步
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
# Authenticate and create the PyDrive client.
# This only needs to be done once per notebook.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
Run Code Online (Sandbox Code Playgroud)
步骤3
file_id = '17Cp4ZxCYGzWNypZo1WPiIz20x06xgPAt' # URL id.
downloaded = drive.CreateFile({'id': file_id})
downloaded.GetContentFile('shaurya.txt')
Run Code Online (Sandbox Code Playgroud)
步骤4
!ls #to verify content
Run Code Online (Sandbox Code Playgroud)
或者
import os
print(os.listdir())
Run Code Online (Sandbox Code Playgroud)
您需要定义一个 Drive API 服务客户端来与 Google Drive API 交互,例如:
from googleapiclient.discovery import build
drive_service = build('drive', 'v3')
Run Code Online (Sandbox Code Playgroud)
(请参阅笔记本外部数据:驱动器、表格和云存储/驱动器 REST API)
| 归档时间: |
|
| 查看次数: |
7672 次 |
| 最近记录: |