【问题标题】:How to save an np.array on google drive using colab?如何使用 colab 在谷歌驱动器上保存 np.array?
【发布时间】:2021-07-16 03:36:07
【问题描述】:

我在 Colab 中编写了一个程序,程序的结果是 np.arrays。请告诉我如何将数组保存到文件中,然后如何从文件中读取?

我读了这条指令:https://colab.research.google.com/notebooks/io.ipynb#scrollTo=S7c8WYyQdh5i

因此,我想出了如何连接到谷歌驱动器以及如何在我需要的目录中创建和上传文本文件。

from google.colab import drive
drive.mount('/content/drive')

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)

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

我也知道你可以像这样将数组保存为文本文件:

import numpy as np
a = np.array([1, 2, 3, 4, 5])
np.savetxt ("array.txt", a, fmt = "% s")

但我不知道如何将此文本文件保存到谷歌驱动器。以及如何从中读取数组?

【问题讨论】:

    标签: python numpy google-colaboratory


    【解决方案1】:

    这会将文件放在云端硬盘的顶层 (https://drive.google.com/drive/my-drive):

    import numpy as np
    
    from google.colab import drive
    drive.mount('/content/drive')
    
    a = np.array([1, 2, 3, 4, 5])
    
    with open('/content/drive/My Drive/array.txt', 'w') as f:
        np.savetxt(f, a)
    

    然后您可以使用它来将数组读回numpy

    with open('/content/drive/My Drive/array.txt', 'r') as f:
        a = np.loadtxt(f)
    

    【讨论】:

      猜你喜欢
      • 2020-07-30
      • 2018-10-14
      • 2021-07-07
      • 2020-04-30
      • 1970-01-01
      • 2021-03-25
      • 2018-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多