Sublime Forum

Make subs create directory if it does not exist

#1

Is there a way to achieve this?

$ subl /existing_folder/non_existing_folder/file

Saving this gives me:

**Unable to save ~//existing_folder/non_existing_folder/file**
**Error: No such file or directory**

Is there a way to create the non existent directories in the way like

$ mkdir -p /existing_folder/non_existing_folder/second_non_existing_directory

Will create both directories.

0 Likes

#2

You can use a plugin like the one below to do this; it listens for when a file is about to be saved and then tries to create the directory structure for the file if it doesn’t exist. This mimics what you would do manually in a case such as this.

It would also be possible to create a shell script wrapper around subl that uses basename in combination with mkdir -p in order to create the folder structure before it invokes subl, though in that case the path would always be created whereas here it’s only created if you actually save the file, which may or may not be more desirable.

If you’re not sure how to use plugins, this video covers how you would do so.

import sublime
import sublime_plugin

import os


class CreateMissingFilePathListener(sublime_plugin.EventListener):
    def on_pre_save(self, view):
        directory = os.path.dirname(view.file_name())
        if not os.path.exists(directory):
            os.makedirs(directory, exist_ok=True)
0 Likes