文件未找到错误:[Errno 2] 没有这个文件或目录,谷歌Colab。

25
每次在我的本地驱动器上运行Python代码时,我都会遇到这个错误。我正在使用以下代码从我的驱动器导入数据。
from google.colab import drive
drive.mount('/content/drive')

这个目录在你的电脑上存在吗? - Federico klez Culloca
8个回答

28

检查你的文件是否存在于 "/content/drive/" 这个位置。

import os
os.chdir("/content/drive/")
!ls

最有可能是在“我的云端硬盘”下面

import os
os.chdir("/content/drive/My Drive")
!ls

1
这也解决了“FileNotFound:“/content/drive/My”的问题,因为My和Drive之间有空格。 - chikitin
对我也不起作用,我只是得到了以下错误:FileNotFoundError: [Errno 2] No such file or directory: '/content/drive/'。你确定它是在Windows下工作的吗? - Eli Borodach
Eli,当你使用正则表达式时,它可以在Windows下工作。例如,它可以是os.chdir(r"/cotent/drive/My Drive")。这样就可以避免由My和Drive之间的空格引起的错误。 - Dismas

8

首先,检查路径。确保文件存在于正确的路径中。

如何确定呢?

很简单。只需使用类似我的示例的终端代码:

!ls /content/drive/My\ Drive/data/sahamyab

colabs 响应:data.jl sahamyab.zip tweets.json

如果您的文件不在该路径上,则您走错了路。否则,在您看到该文件存在之后,只需像这样打开它:

open("/content/drive/My Drive/data/sahamyab/tweets.json")

警告:仔细查看路径。第一个路径中有My\ Drive,而第二个路径中有My Drive。因为第一个路径是终端路径,空格用\ 表示,但第二个路径在Python路径中。


2

谷歌已更名为Mydrive并删除了空格。因此没有"My Drive",而是"MyDrive"。 os.chdir('/content/gdrive/MyDrive/iss/vse/data/')


1
os.chdir('/content/drive/MyDrive')
ls

检查文件是否存在

在驱动器内创建新目录时,请尽量避免使用空格,因为这可能会导致编译时错误。

如果您只想将驱动器挂载到Colab,则可以使用Web IDE而无需任何代码来完成。

enter image description here


1

当我使用以下正则表达式时,遇到了问题。您可能也想尝试一下。

import os
os.chdir(r"/content/drive/My Drive")

请注意正则表达式中 r 的位置。

1
为了解决问题并在Google Colab中查找和加载本地数据文件,请按以下步骤操作:
  1. 从您的系统内存上传数据文件到Google驱动器:
  2. 在Colab中挂载Google驱动器: 2.1)在您的代码中导入: from google.colab import drive 2.2)挂载包含数据的目录到Google驱动器: drive.mount('/content/gdrive') 2.3)要挂载目录,需要授权您的Google账户。
  3. path = "/gdrive/My Drive/filename"

参考链接: Load local data files to Colaboratory


0

在Google Drive中运行Python文件;

!python3 /content/drive/My\ Drive/data/file.py

0

我遇到了同样的问题,对我来说是因为“drive”需要拼写为带有字母“r”的“driver”。 包括空格的"My Drive"也适用于我。

os.chdir('/content/driver/My Drive/*filename*/')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接