sqlite3.OperationalError: unable to open database file (and attempt to write a readonly database): how to fix it
sqlite3.OperationalError: unable to open database file means SQLite could not open or create the file at the path it was given: the folder does not exist, a relative path was resolved from another working directory, or the folder is not writable. Attempt to write a readonly database means the file opened, but only for reading. SQLite also writes -journal and -wal files next to the database, so the folder must be writable, not just the file.
By Livops team, the people who build and run LivopsUpdated
The bot worked on your laptop. Deployed, it stops at the first database call:
sqlite3.OperationalError: unable to open database file
or it starts, answers /start, and fails the first time it saves something:
sqlite3.OperationalError: attempt to write a readonly database
Those are SQLite’s own texts for its result codes SQLITE_CANTOPEN and SQLITE_READONLY[4], raised in Python as OperationalError[6]. In Node.js the sqlite3 package puts the code’s name in front of the same text and sets errno and code on the error[10]:
Error: SQLITE_CANTOPEN: unable to open database file
better-sqlite3 throws a SqliteError whose code is the extended result code[7], and before it even opens the file it checks the folder[8]:
TypeError: Cannot open database because the directory does not exist
This page explains what each error means, gives the fix for each cause, most common first, shows how to see where the file actually goes, and ends with where a SQLite file belongs on Livops.
What do the two errors mean?
unable to open database file is SQLITE_CANTOPEN, code 14: SQLite could not open a file, and it may be the database itself or one of several temporary files[1]. When opening for reading and writing fails, SQLite tries once more read-only; if that fails too, the result is SQLITE_CANTOPEN[5]. Two extended codes narrow it down: SQLITE_CANTOPEN_ISDIR, the path is really a directory, and SQLITE_CANTOPEN_FULLPATH, the system could not turn the file name into a full path[1].
attempt to write a readonly database is SQLITE_READONLY, code 8: the connection tried to change data it has no write permission for[1]. The open itself worked. If the operating system will not let SQLite open the file for writing, SQLite opens it read-only instead[3][5], so reads succeed and the first INSERT fails. Its extended codes tell you which part is read-only[1]:
| Extended code | What is read-only |
|---|---|
SQLITE_READONLY_DIRECTORY |
The folder: SQLite may not create a journal file next to the database, and it needs one to write |
SQLITE_READONLY_CANTLOCK |
The -shm file of a WAL-mode database |
SQLITE_READONLY_RECOVERY |
A WAL-mode database needs recovery, which needs write access |
Why the folder matters. A database is more than one file. The rollback journal is always in the same folder as the database, named after it with -journal added, and it is created when a transaction starts[2]. In WAL mode the -wal and -shm files sit in the same folder too[2]. So SQLite needs to write to the folder, not only to the .db file.
Causes, most common first
1. The folder does not exist
SQLite creates the database file when it is missing[3], but it puts it in the folder the path names, and that folder has to be there. sqlite3.connect("data/bot.db") with no data folder ends in unable to open database file. A .gitignore that keeps data/ out of the repository is one way the folder goes missing on the server while it exists on your laptop.
Fix: create the folder before you connect.
import os, sqlite3
os.makedirs("data", exist_ok=True)
db = sqlite3.connect("data/bot.db")
import fs from 'node:fs'
import Database from 'better-sqlite3'
fs.mkdirSync('data', { recursive: true })
const db = new Database('data/app.db')
2. A relative path, resolved from another working directory
On Linux and macOS, SQLite turns a path that does not start with / into a full path by putting the process’s current working directory in front of it[5]. bot.db is not “next to my script”: it is next to wherever the process was started. You run python bot.py from the project folder and the file is found; a service manager, a Docker WORKDIR, a cron job, or python src/bot.py from one level up starts it somewhere else, and SQLite looks, or tries to create, in the wrong place.
Fix: use an absolute path. Build it from a variable, or from the script’s own location:
import sqlite3
from pathlib import Path
DB = Path(__file__).resolve().parent / "data" / "bot.db"
DB.parent.mkdir(parents=True, exist_ok=True)
db = sqlite3.connect(DB)
3. The code folder is read-only
Some platforms and containers run your code from a folder the app may not write to. Then both errors appear, depending on whether the file was shipped:
- The database file is not in the repository: SQLite cannot create it, so
unable to open database file. - You committed
bot.db: the file exists, SQLite opens it read-only[3], the bot reads its data, and the first write fails withattempt to write a readonly database.
Fix: keep the database outside the code, in the folder the platform gives you for data, and do not ship a database file with the code. On Livops that folder is /app/data; see below.
4. Permissions: the file is writable, the folder is not
A common half-fix is chmod 666 bot.db. It does not help when the folder belongs to another user: SQLite still cannot create bot.db-journal there, and the write fails with SQLITE_READONLY_DIRECTORY[1][5]. In WAL mode a read-only -shm file gives SQLITE_READONLY_CANTLOCK[1].
Fix: let the user the app runs as write to the folder, not just the file. id shows which user that is, and ls -ld on the folder shows who owns it.
5. It was opened read-only on purpose
A connection opened with mode=ro in a URI fails every write with this same message; Python’s docs use exactly that as their example[6]:
sqlite3.connect("file:tutorial.db?mode=ro", uri=True)
better-sqlite3 has a readonly option[7]. Check that a read-only connection from a reporting script is not the one your app writes with.
How to see where the file actually goes
Print the working directory and the full path the app will open, and check that the folder is writable, from inside the deployed app rather than your laptop:
import os
path = "bot.db"
full = os.path.abspath(path)
print("cwd:", os.getcwd())
print("db:", full)
print("folder writable:", os.access(os.path.dirname(full), os.W_OK))
On Python 3.11 and later, the exception also carries sqlite_errorcode and sqlite_errorname, SQLite’s numeric code and its name[6]. With node-sqlite3, the error event or the callback’s first argument holds the error[9], with the same name in code[10].
On Livops
What Livops’s Files and data says, in short:
- The code is read-only. While an app or bot runs, its code is read-only. The code folder,
/app, is not writable, so a database file can be neither created nor changed there. /app/datais kept. It is the project’s own disk, kept across deploys and restarts, for database files, uploads and sessions. Its path is also in theDATA_DIRvariable: read it from there rather than hard-coding it./tmpis writable too, but it is wiped on every restart and deploy and holds 128 MB, so it is for scratch files only.- A
datafolder in your repository is covered. If the repository has adatafolder, the disk covers it, and the files in it are not visible to the running app. Abot.dbcommitted there is not the one the app sees. - Dockerfile projects. A project that runs from a Dockerfile or a ready image gets the disk at
/data, withDATA_DIR=/data.
A literal file name lands on the disk by itself. In the docs’ words, “a SQLite file whose name is written literally in the code is linked to the disk for you”. Their examples:
sqlite3.connect('bot.db')- SQLAlchemy:
sqlite:///app.db - better-sqlite3:
new Database('app.db')
That file is written to /app/data and survives a deploy. If the name comes from a variable or a config file, the platform cannot see it, so take the path from DATA_DIR instead. The docs’ examples:
import os, sqlite3
db = sqlite3.connect(os.path.join(os.environ["DATA_DIR"], "bot.db"))
import path from 'node:path'
import Database from 'better-sqlite3'
const db = new Database(path.join(process.env.DATA_DIR ?? 'data', 'app.db'))
For Prisma, add this to the project’s variables:
DATABASE_URL=file:/app/data/app.db
When to use PostgreSQL instead. The disk belongs to one app: no other service sees it, and it is not backed up. SQLite is fine for a small bot or a prototype. Once there are customers, orders or payments, open a PostgreSQL database: it is backed up every night, and its address, DATABASE_URL, is written as a variable to every service in the environment, so a bot, a web app and a worker can share it. A bot costs 19 credits a month; a database is free at 500 MB, one per team, and 1 GB is 9 credits a month. More on running a bot for good: Keep a Telegram bot running 24/7.
Questions
Why does SQLite say unable to open database file when the file does not exist yet?
SQLite creates a missing database file, but only inside a folder that exists and that the process may write to. If the folder is missing, or the path points somewhere else than you think, the file cannot be created and you get this error.
Why can my app read the database but not write to it?
When SQLite cannot open the file for writing because of operating system permissions, it opens it read-only instead. Reads work, and the first write fails with attempt to write a readonly database. The same error comes when the folder is read-only and SQLite cannot create its journal file there.
Does the folder need to be writable, or only the database file?
The folder too. The rollback journal, and in WAL mode the -wal and -shm files, are always created in the same folder as the database, with the database's name plus a suffix.
Why does it work from the project folder and fail under a service manager, Docker or cron?
Because the path is relative. SQLite puts the current working directory in front of a path that does not start with a slash, so bot.db means a different file for every directory the process is started from. Use an absolute path, or build it from a variable.
What is SQLITE_CANTOPEN in Node.js?
The name of SQLite's result code 14, unable to open database file. The sqlite3 package puts it in front of the message and in the error's code property; better-sqlite3 puts the extended code in code. better-sqlite3 also checks the folder itself and throws Cannot open database because the directory does not exist.
Where should a bot keep its SQLite file on Livops?
In /app/data, the project's own disk, whose path is also in the DATA_DIR variable. It is kept across deploys and restarts. The code folder is not writable while the app runs, and /tmp is wiped on every restart and deploy.
Is SQLite enough for a production bot?
For a small bot or a prototype, yes. The disk belongs to one app, no other service sees it, and it is not backed up. Once there are customers, orders or payments, Livops's docs recommend a PostgreSQL database, which is backed up and can be used by several services.
Sources
- SQLite — Result and Error Codes (sqlite.org). Checked .
- SQLite — Temporary Files Used By SQLite (sqlite.org). Checked .
- SQLite — Opening A New Database Connection (sqlite.org). Checked .
- SQLite source — src/main.c (sqlite3ErrStr) (sqlite.org). Checked .
- SQLite source — src/os_unix.c (sqlite.org). Checked .
- Python docs — sqlite3 (docs.python.org). Checked .
- better-sqlite3 — API docs (raw.githubusercontent.com). Checked .
- better-sqlite3 source — lib/database.js (v13.2.0) (raw.githubusercontent.com). Checked .
- node-sqlite3 — API (github.com). Checked .
- node-sqlite3 source — src/macros.h (raw.githubusercontent.com). Checked .
Put your project online today
Connect GitHub or drop a folder. No card is asked for.
Deploy your botRelated
- aiogram bot hosting: how to deploy an aiogram 3 botAn aiogram 3 bot needs one process that never stops, the token in an environment variable, state kept outside memory and a clean exit on SIGTERM. On Livops you push a repository with bot.py and requirements.txt, and it runs for 19 credits a month (19,000 so'm), polling or webhook.
- How to keep a Telegram bot running 24/7A bot run with python bot.py or node bot.js stops when the terminal closes, the laptop sleeps or the code crashes, and two copies polling one token knock each other off with 409 Conflict. Keep exactly one copy running under something that restarts it — systemd, Docker or a platform — and stop it cleanly on SIGTERM. On Livops a bot runs from a push for 19 credits a month (19,000 so'm).
- Telegram bot hosting in 2026: the options comparedA Telegram bot needs a process that never stops, or a public HTTPS address for a webhook. On Livops it runs from a GitHub push for 19 credits a month (19,000 so'm). Here is how a VPS, Railway, Render, Fly.io and Vercel compare.
- python-telegram-bot hosting: deploying a v22 botA python-telegram-bot bot runs as one Application: run_polling() for polling, run_webhook() with the webhooks extra for a webhook. Both stop cleanly on SIGTERM. On Livops it runs from a push with bot.py and requirements.txt for 19 credits a month (19,000 so'm).
- Managed PostgreSQL hosting in 2026: the options comparedA production PostgreSQL needs backups you can restore, a connection limit your app stays under, the app in the same region, and a supported version. On Livops a PostgreSQL 15, 16 or 17 database runs inside your project, its DATABASE_URL is written into your services, and it is backed up every night; 500 MB is free, one per team, and 1 GB is 9 credits a month. Here is how the paid plans of Neon, Supabase, Render, Railway and a VPS compare; free tiers have their own page.
- Free PostgreSQL hosting in 2026: every free tier comparedThe best free PostgreSQL hosting in 2026 is Neon (1 GB per project, never paused for inactivity, no card), Prisma Postgres (2 GB within 200,000 operations a month) and Nile (1 GB, never pauses); Supabase adds auth and storage but pauses after a week idle. Render's free database is deleted 30 days after creation plus 14 days' grace, and most free tiers have no backups. On Livops one 500 MB database per team is free and backed up nightly, but it starts only once the account has credits and only apps on Livops can reach it.
- Binary was compiled with 'CGO_ENABLED=0', go-sqlite3 requires cgo to work. This is a stub: how to fix itBinary was compiled with 'CGO_ENABLED=0', go-sqlite3 requires cgo to work. This is a stub means the program was built without cgo, so mattn/go-sqlite3 compiled its placeholder driver, which fails on every connection. Build with CGO_ENABLED=1 and a C compiler such as gcc, or switch to a pure-Go SQLite driver like modernc.org/sqlite, registered as sqlite rather than sqlite3, which builds with cgo off.