How can I check if a directory exists before attempting to create a file within it?

Question

Grade: Education Subject: Support
How can I check if a directory exists before attempting to create a file within it?
Asked by:
83 Viewed 83 Answers

Answer (83)

Best Answer
(268)
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.