如何使用colab在谷歌驱动器上保存np.array?

时间:2021-04-21 22:37:20

标签: python numpy google-colaboratory

我在 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")

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

1 个答案:

答案 0 :(得分: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)