FileNotFoundError
builtins.FileNotFoundError
Stack trace
Traceback (most recent call last):
File "app.py", line 25, in <module>
storage_context = StorageContext.from_defaults(persist_dir="./storage")
File "/usr/local/lib/python3.9/site-packages/llama_index/storage/storage_context.py", line 45, in from_defaults
raise FileNotFoundError(f"Persist directory {persist_dir} not found.")
FileNotFoundError: Persist directory ./storage not found. Why it happens
LlamaIndex requires a valid directory path to persist its index data. If the directory does not exist or the path is incorrect, the library raises a FileNotFoundError. This usually happens when the directory was never created or the path is mistyped.
Detection
Check for FileNotFoundError exceptions when initializing StorageContext with a persist_dir parameter, and verify the directory path exists before running the code.
Causes & fixes
The persist directory path does not exist on the filesystem.
Create the directory manually before running the code or add code to create it programmatically using os.makedirs(persist_dir, exist_ok=True).
The persist_dir path is incorrectly specified or has a typo.
Verify and correct the persist_dir string to point to the correct existing directory path.
The application lacks filesystem permissions to access or create the directory.
Ensure the running user has read/write permissions for the directory path or choose a directory with proper access rights.
Code: broken vs fixed
from llama_index import StorageContext
# This will raise FileNotFoundError if './storage' does not exist
storage_context = StorageContext.from_defaults(persist_dir='./storage') # Error here import os
from llama_index import StorageContext
persist_dir = './storage'
os.makedirs(persist_dir, exist_ok=True) # Create directory if missing
storage_context = StorageContext.from_defaults(persist_dir=persist_dir) # Fixed
print('StorageContext initialized successfully') Workaround
Wrap the StorageContext initialization in try/except FileNotFoundError and create the directory dynamically if caught, then retry initialization.
Prevention
Always verify and create the persist directory path during application startup or deployment to avoid runtime directory not found errors.