Last Updated: November 19, 2020
· croaky

Fix "Can't open file for writing" in Vim

I learned this tip watching Sean Griffin in Hands-On Backbone.js on Rails.

The error

Edit a new file in a directory that does not exist yet, such as app/views/application:

:e app/views/application/index.html.erb

Try to save the file:


An error will display:

"app/views/application/index.html.erb" E212: Can't open file for writing
Press ENTER or type command to continue

The error means is it can't save the file because app/views/application doesn't exist. So, we have to create it.

Making the directory in the shell

I used to suspend Vim:


Then, create the directory from the shell:

mkdir app/views/application

Then, bring Vim back to the foreground:


Making the directory in Vim

What Sean does in Hands-On Backbone.js on Rails is create the directory right from Vim:

:!mkdir -p %:h

Much faster!

How it works

% is the current file in Vim. %:h is the directory in which the current file is located. So, when editing app/views/application/index.html.erb, the command expands to mkdir -p app/views/application.


For the fastest approach yet, use vim-mkdir to just automatically make the directory when it doesn't exist, with no manual intervention necessary.

Related protips:

Basic Vim commands - For getting started

2 Responses
Add your response

Is there a similar solution for when we have no write permissions to a catalog and have to restart vim with sudo?

over 1 year ago ·

@jimmykane thanks!

over 1 year ago ·