Moving the directory creation logic so that it only creates a directory if it is required to write a file