Skip to content

/errors/vim/e212-cant-open-file-for-writing

Vim E212: Can't open file for writing

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · VIM - Vi IMproved 9.2 (2026 Feb 14updated
tool
Vim / Neovim
versions
Vim 8.x, Vim 9.x
os
linux, macos, windows

E212: Can't open file for writing means Vim could not create or open the file at the path of the buffer: the directory does not exist, or you lack permission to write there (for example /etc/nginx/nginx.conf opened without sudo). Your changes are still in the buffer. Create the missing directory, or save with root rights via :w !sudo tee % > /dev/null, or write a copy to a path you own.

Reproduce it

Writing into a directory that does not exist, in Vim's batch mode, printing the message Vim reported:

bash
printf 'one\n' > a.txt
vim -Nu NONE -i NONE -es \
  -c 'silent! write nodir/out.txt' \
  -c 'call writefile([v:errmsg], "error.txt")' \
  -c 'qa!' a.txt
cat error.txt

Output

"nodir/out.txt" E212: Can't open file for writing

Fix: the directory is missing

mkdir() with the p flag creates every missing parent directory, like mkdir -p. expand('%:p:h') is the directory of the current file:

bash
vim -Nu NONE -i NONE -es \
  -c 'normal! ihello' \
  -c "call mkdir(expand('%:p:h'), 'p')" \
  -c 'write' \
  -c 'qa!' new/dir/notes.txt
cat new/dir/notes.txt

Output

hello

Interactively: :call mkdir(expand('%:p:h'), 'p') and then :w. Neovim also accepts :w ++p, which creates the directories while writing.

Fix: no permission (system files)

On Linux and macOS, pipe the buffer through sudo tee and let it write the file as root:

vim
:w !sudo tee % > /dev/null

% is the current file name. Vim then notices the file changed on disk; press L to reload it, or O. A cleaner habit is to open system files with sudoedit /etc/nginx/nginx.conf (or sudo -e), which edits a temporary copy as your user and installs it as root.

  • E45: 'readonly' option is set (add ! to override): the file is read-only for Vim (opened with view or vim -R, or with a read-only attribute). :w! overrides it if you have permission.
  • E505: "file" is read-only (add ! to override): the file has no write permission bit; :w! tries anyway, which works if you own the directory.

Sources