You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在本地Anaconda的JupyterLab中像Colab一样挂载并访问Google Drive?

如何在本地Anaconda的JupyterLab中像Colab一样挂载并访问Google Drive?

当然可以做到啦!之前用jupterdrive踩坑没关系,我给你分享两个实测好用的方法,帮你在本地Anaconda的JupyterLab里顺畅挂载Google Drive:

方法一:使用pydrive2库(推荐,配置简单易上手)

这个库是PyDrive的升级版,维护更活跃,适配性也更好:

  • 第一步:先在你的Anaconda环境里安装库
    打开Anaconda Prompt或者JupyterLab的终端,运行:
    conda install -c conda-forge pydrive2
    # 或者用pip安装(如果conda源慢的话)
    # pip install pydrive2
    
  • 第二步:配置Google Drive API凭证
    你需要先去Google Cloud Console做几个简单操作:创建新项目 → 启用Google Drive API → 创建桌面应用类型的OAuth客户端ID → 下载JSON格式的凭证文件,把它重命名为client_secrets.json,放到你的JupyterLab工作目录里。
  • 第三步:在JupyterLab里运行挂载代码
    新建一个Notebook,粘贴以下代码:
    from pydrive2.auth import GoogleAuth
    from pydrive2.drive import GoogleDrive
    
    # 初始化认证对象
    gauth = GoogleAuth()
    # 启动本地网页认证(会自动弹出浏览器,让你登录Google账号授权)
    gauth.LocalWebserverAuth()
    # 创建Drive操作实例
    drive = GoogleDrive(gauth)
    
    # 测试一下:列出Google Drive根目录的文件
    file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
    for file in file_list:
        print(f"文件名: {file['title']}, 文件ID: {file['id']}")
    
    运行后,只要授权成功,就能看到你的Drive文件列表啦!后续可以用drive.CreateFile()上传文件,file.GetContentFile()下载文件到本地。

方法二:使用Google官方API库(更灵活,适合复杂操作)

如果需要做更复杂的Drive操作(比如批量修改文件权限、文件夹管理),可以用这套官方工具:

  • 第一步:安装依赖库
    在终端运行:
    conda install -c conda-forge google-api-python-client google-auth-httplib2 google-auth-oauthlib
    
  • 第二步:同样准备好上面的client_secrets.json凭证文件
  • 第三步:运行挂载代码
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    import os
    
    # 定义权限范围:如果需要修改Drive文件,把下面的权限换成'https://www.googleapis.com/auth/drive'
    SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
    
    def mount_drive():
        creds = None
        # 如果之前授权过,会生成token.json,直接加载即可
        if os.path.exists('token.json'):
            creds = Credentials.from_authorized_user_file('token.json', SCOPES)
        # 没有有效凭证的话,启动授权流程
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'client_secrets.json', SCOPES)
                creds = flow.run_local_server(port=0)
            # 保存凭证,下次启动不用重复授权
            with open('token.json', 'w') as token:
                token.write(creds.to_json())
    
        try:
            # 创建Drive服务实例
            service = build('drive', 'v3', credentials=creds)
            # 列出根目录的前10个文件
            results = service.files().list(pageSize=10, fields="nextPageToken, files(id, name)").execute()
            items = results.get('files', [])
            if not items:
                print("你的Drive根目录里没有文件哦~")
                return
            print("Google Drive根目录文件列表:")
            for item in items:
                print(f"{item['name']} ({item['id']})")
        except HttpError as error:
            print(f"操作出错啦:{error}")
    
    if __name__ == '__main__':
        mount_drive()
    

小提示

  • 第一次运行代码时,会自动弹出浏览器让你登录Google账号,确认授权给这个应用即可,授权后会生成token.json文件,下次启动就不用重复授权了。
  • 之前jupterdrive不好用,大概率是因为它的维护不及时,上面这两个方案都是基于Google官方生态的工具,稳定性和兼容性都靠谱得多。

备注:内容来源于stack exchange,提问作者sakthivel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 08:20:29