pgref.dev/sqlite/errors/SQLITE_CANTOPEN
SQLITE_CANTOPENERRORTier 1 — Safe✅ HIGH confidence

unable to open database file

Category: File AccessVersions: All SQLite versions

What this means

SQLITE_CANTOPEN (result code 14) is returned when SQLite cannot open the specified database file. This occurs at connection time, before any SQL is executed. Common causes include the directory not existing, insufficient permissions, or a too-long path. In WAL mode, failure to create the -wal or -shm sidecar files also produces this error.

Why it happens

  1. 1The directory containing the database file does not exist
  2. 2The process lacks read permission on the database file
  3. 3The process lacks write permission on the containing directory (needed to create the journal or WAL sidecar files)
  4. 4The path exceeds the OS maximum path length
  5. 5The temporary directory (for in-memory or :memory: URIs) is unavailable

How to reproduce

Connecting to a database in a directory that does not exist.

trigger — this will ERROR
import sqlite3
# The directory /nonexistent/path/ does not exist
conn = sqlite3.connect('/nonexistent/path/demo.db')  # triggers SQLITE_CANTOPEN
sqlite3.OperationalError: unable to open database file

Fix 1: Create the parent directory before connecting

When the database path is in a directory that may not yet exist.

fix
import sqlite3, os

db_path = '/var/data/myapp/demo.db'
os.makedirs(os.path.dirname(db_path), exist_ok=True)
conn = sqlite3.connect(db_path)

Why this works

os.makedirs with exist_ok=True creates all intermediate directories atomically. SQLite then finds the parent directory and can create or open the database file.

What not to do

Silently fall back to :memory: when the file cannot be opened

Why it's wrong: In-memory databases are lost when the connection closes. If the application expects persistent storage and silently falls back, all data written during the session will be lost.

Version notes

SQLite 3.7.17+SQLITE_CANTOPEN_NOTEMPDIR (270) extended code introduced — emitted when a temporary file needed for sorting or WAL cannot be created because TMPDIR is unavailable or full.

Sources

📚 Official docs: https://www.sqlite.org/rescode.html#cantopen

🔧 Source ref: sqlite3.h — SQLITE_CANTOPEN = 14

📖 Further reading: SQLite URI filenames

Confidence assessment

✅ HIGH confidence

Stable. The set of OS conditions that trigger this code is consistent across platforms, though exact error messages differ.

See also

⚙️ This error reference was generated with AI assistance and reviewed for accuracy. Examples are provided to illustrate common scenarios and may not cover every case. Always test fixes in a development environment before applying to production. Spotted an error? Suggest a correction →