You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Google Colab中使用os.listdir出现FileNotFoundError如何解决?

问题:Google Colaboratory加载本地文件时出现FileNotFoundError

我在Google Colaboratory中跟着教程从本地文件加载数据,代码如下:

import numpy as np #To do relay operations
import matplotlib.pyplot as plt #to show image
import os #Iterate through directories and join paths
import cv2 #To do image operations

DATADIR = "C:\\Users\\Family\\Desktop\\Nottingham\\Year 4\\FYP\\Software\\Datasets\\PetImages"
CATEGORIES = ["Dog","Cat"]

for category in CATEGORIES:
  path = os.path.join(DATADIR,category) #path to cats or dogs dir
  print(category)
  print(path)
  for img in os.listdir(path):
    print(img)
    img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)
    plt.imshow(img_array, cmap = "gray")
    plt.show()
    break
    break

运行时第13行出现如下错误:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\Family\Desktop\Nottingham\Year 4\FYP\Software\Datasets\PetImages/Dog'

我已多次确认本地该目录确实存在,但错误仍持续出现。尝试了三种路径格式修改都无效:

DATADIR = "C:\\Users\\Family\\Desktop\\Nottingham\\Year 4\\FYP\\Software\\Datasets\\PetImages"

DATADIR = "C:/Users/Family/Desktop/Nottingham/Year 4/FYP/Software/Datasets/PetImages"

DATADIR = r"C:\Users\Family\Desktop\Nottingham\Year 4\FYP\Software\Datasets\PetImages"

请问还有什么其他解决办法?


解决办法

Google Colaboratory是云端运行环境,无法直接访问你本地Windows系统的C:\路径,这是核心问题,以下是可行的解决方式:

1. 直接上传数据集到Colab会话

使用Colab内置的文件上传工具,将本地的PetImages文件夹上传到当前会话:

from google.colab import files
import os

# 上传文件夹(需手动选择本地的PetImages文件夹)
uploaded = files.upload()

# 确认上传后的路径,修改DATADIR为当前会话中的路径
DATADIR = "./PetImages"

上传完成后,可通过os.listdir(DATADIR)验证目录是否存在。

2. 挂载Google Drive存储

将数据集上传到你的Google Drive,然后在Colab中挂载Drive,直接读取云端文件:

from google.colab import drive
import os

# 挂载Drive,按提示完成授权
drive.mount('/content/drive')

# 修改DATADIR为Drive中数据集的实际路径
DATADIR = "/content/drive/MyDrive/Datasets/PetImages"

3. 检查路径大小写匹配

Colab运行在Linux环境下,路径是大小写敏感的。确认CATEGORIES中的"Dog"、"Cat"和实际目录的大小写完全一致(比如不能写成"dog"或"cat")。


内容的提问来源于stack exchange,提问作者Zelreedy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 10:50:37