我试图从我的谷歌驱动器下载文件到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()))
这样做我得到这个错误:
NameError: name 'drive_service' is not defined
如何删除此错误?
从谷歌驱动器下载文件到colab笔记本的最简单方法是通过协作API:
from google.colab import drive
drive.mount('/content/gdrive')
!cp '/content/gdrive/My Drive/<file_path_on_google_drive>' <filename_in_colabo>
备注:
您需要定义驱动器API服务客户端以与Google驱动器API进行交互,例如:
from googleapiclient.discovery import build
drive_service = build('drive', 'v3')
(见笔记本External data: Drive, Sheets, and Cloud Storage/Drive REST API)
我建议您使用Pydrive从谷歌驱动器下载您的文件。我下载500MB数据集5s。 1.安装Pydrive
!pip install PyDrive
道琼斯
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
3.从谷歌驱动器下载文件的代码
fileId = drive.CreateFile({'id': 'DRIVE_FILE_ID'}) #DRIVE_FILE_ID is file id example: 1iytA1n2z4go3uVCwE_vIKouTKyIDjEq
print fileId['title'] # UMNIST.zip
fileId.GetContentFile('UMNIST.zip') # Save Drive file as a local file
Sher Mo Jihad
步骤1
!pip install -U -q PyDrive
第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)
第三步:
file_id = '17Cp4ZxCYGzWNypZo1WPiIz20x06xgPAt' # URL id.
downloaded = drive.CreateFile({'id': file_id})
downloaded.GetContentFile('shaurya.txt')
第4步
!ls #to verify content
要么
import os
print(os.listdir())
这是一个简单的方法。您可以使用Python中的wget命令或请求模块来完成工作。
# 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
可以将file_download_link
中的字符串粘贴到浏览器地址栏中以直接获取下载对话框。
如果您使用wget命令:
!wget -O ebook.pdf --no-check-certificate "$file_download_link"
您还可以在https://github.com/ruelj2/Google_drive上使用google.colab和PyDrive上的实现,这样可以更轻松。
!pip install - U - q PyDrive
import os
os.chdir('/content/')
!git clone https://github.com/ruelj2/Google_drive.git
from Google_drive.handle import Google_drive
Gd = Google_drive()
Gd.load_file(local_dir, file_ID)