使用 Google Colab 上传本地文件

Upload local files using Google Colab

正在尝试使用 Google Collaboratory 以这种方式上传本地文件:

from google.colab import files
uploaded = files.upload()

我收到以下错误:

Upload widget is only available when the cell has been executed in the current browser session. Please rerun this cell to enable.

我重新运行单元格,但它不起作用...

听起来 第三方 cookies 可能在您的浏览器中被禁用,请参阅 https://github.com/googlecolab/colabtools/issues/17

设置在chrome://settings/content/cookies.

上传按钮后的文字非常通用:

[ Choose Files ]   Upload widget is only available when the cell has been executed in the current browser session. Please rerun this cell to enable.

这是为您或其他人从另一台计算机或window的浏览器打开共享笔记本的情况准备的文本。如果上传小部件由于某些安全或隐私保护而被阻止,它也会保持显示。之前通常会显示一个重要的错误消息框。

如果您最近从同一个 window 获得了 运行 单元格,那么重新 运行 它是没有用的,如果两者之间没有固定设置。

tl;dr) 文件上传需要在 Chrome 中启用第三方 cookie(上面的答案 - Chrome settings / Conntent settings / Block third-party cookie 和站点数据 - 取消选中)。在 Firefox 中是


Chrome 或新版 Firefox
如果您 禁用 third-party cookies 您会看到这个消息框(当任何第一个输出单元格第一次在笔记本中显示时,它只显示一次,可能是在启动时):

Error
Could not access the resources needed to display output.
This is probably because third-party cookies are not allowed by your browser.

  Details... [ V unfold to see details ]

这些细节是相似的:

Chrome: NotSupportedError: Failed to register a ServiceWorker: The user denied permission to use Service Worker
Firefox: SecurityError: The operation is insecure.

他们希望您在很久以后看到带有此内部 的回溯时还记得它。 MessageError 的回溯每次都是相同的,因为它包含从 javascript 通过管道复制的错误。

Chrome: MessageError: TypeError: Cannot read property '_uploadFiles' of undefined
Firefox: MessageError: TypeError: google.colab._files is undefined


旧版 Firefox 52 ESR(扩展支持版本 - 仍然有新的安全更新)
Colab 网站目前从未报告过旧版 Firefox 中人类可理解的消息框,只有回溯。


Colaboratory work relative 在禁用 third-party cookie 的情况下也可以接受。我很想忽略笔记本开始时的一条消息,而更喜欢标准的隐私。我保证,如果我想轻松上传文件或与其他人合作或不喜欢轮子图标,我永远不会禁用它们,因为轮子图标有时会不停地旋转,但实际上什么都没有 运行ning :-)

我刚遇到同样的问题,所以我重新启动内核并刷新页面,问题就消失了。希望对您有所帮助。

您可以在 Chrome 中将以下 cookie 列入白名单:

https://[*.]googleusercontent.com:443

I Gave a similar answer , but will copy it here anyway, just because this question has reached far more users and could help far more people:

我一分钟前遇到了同样的问题,虽然我没能发现错误,但您使用的文件上传方法有 替代方法

您只需点击笔记本边栏上的文件夹图标,然后点击上传按钮,即可在 Colab 中上传您的文件。

要将文件加载到单元格中,例如 csv 文件,您只需编写(如果您使用的是 pandas):

df = pd.read_csv('path_to/my_file.csv')

这应该与浏览器无关。

如果您正在使用 Chrome 试试这个:

  1. 转到 chrome://settings/content/cookies
  2. 关闭-> 阻止第三方 cookie

这个对我有用