FileNotFoundError
builtins.FileNotFoundError
Stack trace
Traceback (most recent call last):
File "train.py", line 42, in <module>
dataset = torchvision.datasets.ImageFolder(root='data/train', transform=transform)
File "/usr/local/lib/python3.9/site-packages/torchvision/datasets/folder.py", line 273, in __init__
raise FileNotFoundError(f"Dataset not found at {root}")
FileNotFoundError: Dataset not found at data/train Why it happens
This error occurs because the path provided to the PyTorch dataset loader does not exist on the filesystem. It can happen if the dataset was not downloaded, the path is misspelled, or the working directory is incorrect.
Detection
Before dataset loading, check if the dataset path exists using os.path.exists() or os.path.isdir() to catch missing paths early and log a clear error message.
Causes & fixes
Dataset directory does not exist at the specified path
Verify the dataset path is correct and the directory exists. Download or extract the dataset to that location before loading.
Relative path used but current working directory is different than expected
Use absolute paths or ensure the script runs with the correct working directory where the dataset path is valid.
Typo or incorrect folder name in the dataset path string
Double-check the folder names and spelling in the dataset path string passed to the dataset loader.
Code: broken vs fixed
import torchvision.datasets as datasets
# This will raise FileNotFoundError if 'data/train' does not exist
train_dataset = datasets.ImageFolder(root='data/train', transform=None) # Error here import os
import torchvision.datasets as datasets
# Use absolute path and check existence before loading
dataset_path = os.path.abspath('data/train')
if not os.path.isdir(dataset_path):
raise FileNotFoundError(f"Dataset path not found: {dataset_path}")
train_dataset = datasets.ImageFolder(root=dataset_path, transform=None) # Fixed
print('Dataset loaded successfully') Workaround
Wrap dataset loading in try/except FileNotFoundError and prompt the user to download or specify the correct dataset path if missing.
Prevention
Use absolute dataset paths and verify dataset presence during setup or initialization steps to avoid runtime path errors.