Ensures that the directory exists when trying to write a file.