【问题标题】:How to export non txt data from Colaboratory to Google Drive?如何将非 txt 数据从 Colaboratory 导出到 Google Drive?
【发布时间】:2018-02-08 17:53:35
【问题描述】:

我正在运行 Colab,我想将一些非 txt 数据(numpy 数组、PIL 图像、.h5 keras/tensorflow 模型)保存到我的驱动器中。

我可以使用此脚本保存 .txt 文件

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

# 1. Authenticate and create the PyDrive client.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default() 
drive = GoogleDrive(gauth)

# PyDrive reference:
# https://googledrive.github.io/PyDrive/docs/build/html/index.html

# 2. Create & upload a file text file.
uploaded = drive.CreateFile({'title': 'Sample upload.txt'})
uploaded.SetContentString('Sample upload file content')
uploaded.Upload()
print('Uploaded file with ID {}'.format(uploaded.get('id')))

# 3. Load a file by ID and print its contents.
downloaded = drive.CreateFile({'id': uploaded.get('id')})
print('Downloaded content "{}"'.format(downloaded.GetContentString()))

但我不能将它用于其他类型的数据。

任何帮助将不胜感激!

【问题讨论】:

    标签: google-colaboratory


    【解决方案1】:

    pydrive 支持上传文件和字符串——参见this sample in the docs

    另外,还可以在创建文件时设置MIME类型,例如

    uploaded = drive.CreateFile({'title': 'sample.csv', 'mimeType': 'text/csv'})
    

    【讨论】:

      【解决方案2】:

      我想出了解决方案:

      假设您在 Colab 上生成了一张图片,并希望将其保存到您 Google 云端硬盘中的特定文件夹中。

      首先保存您的图像,就像您在本地计算机上一样:

      from scipy.misc import imsave
      imsave('my_image.png', my_image)
      

      这允许您将图像“临时”保存在当前工作区中,名称为 my_image.png,但是,它尚未保存到您的磁盘中。

      您现在应该将其上传到您的 Google 云端硬盘。操作方法如下:

      file = drive.CreateFile({'parents':[{u'id': folder_id}]})
      file.SetContentFile('my_image.png')
      file.Upload()
      

      这会将 my_image.png 永久保存在指定文件夹中(其 id 为 folder_id)

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2018-07-13
        • 1970-01-01
        • 2018-08-15
        • 2019-04-20
        • 2018-04-09
        • 2020-12-06
        • 2023-04-04
        • 2018-05-07
        • 2018-08-25
        相关资源
        最近更新 更多