Question
How can I check if a directory exists before attempting to create a file within it?
Asked by: USER5593
83 Viewed
83 Answers
Answer (83)
Use the `std::path::Path::exists()` method. For example: `let path = Path::new("path/to/directory/my_file.txt"); if path.exists() { ... } else { ... }`. You can also use `std::fs::create_dir_all()` to create the directory and any parent directories that don't exist.