本地文件系统

从本地文件系统上传文件

files.upload 会返回已上传文件的字典。 此字典的键为文件名,值为已上传的数据。

from google.colab import files

uploaded = files.upload()

for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))

将文件下载到本地文件系统

files.download 会通过浏览器将文件下载到本地计算机。

from google.colab import files

with open('example.txt', 'w') as f:
  f.write('some content')

files.download('example.txt')

Google 云端硬盘

您可以通过多种方式访问 Google 云端硬盘中的文件,其中包括:

  • 在运行时的虚拟机中装载 Google 云端硬盘
  • 对该 API 使用封装容器(例如 PyDrive2
  • 使用原生 REST API

每个方法的示例如下所示。

在本地装载 Google 云端硬盘

以下示例展示了如何使用授权代码在您的运行时上装载 Google 云端硬盘,以及如何在那里写入和读取文件。一旦执行,您便可以在 https://drive.google.com/ 看到相应的新文件 (foo.txt)。

此操作仅支持读取、写入和移动文件;如需程序化地修改共享设置或其他元数据,请使用以下某一其他选项。

注意:使用文件浏览器中的“装载 Google 云端硬盘”按钮时,对于仅由当前用户修改过的笔记本来说,无需输入验证码。

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

 Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&scope=email%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdocs.test%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.photos.readonly%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fpeopleapi.readonly&response_type=code Enter your authorization code: ·········· Mounted at /content/drive

with o
02-04 13:45