Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
:timing
:sccache 1Tips and Traps¶
This is an unsized type, meaning that it must always be used behind a pointer like & or Box.
For an owned version of this type, see [PathBuf](https://doc.rust-lang.org/nightly/std/path/struct.PathBuf.html).
Methods of
std::path::Pathreturn object of the typestd::ffi::OsStrrather thanstd::Stringor&sstr.The Rust crate normpath provides more reliable path manipulation.
use std::path::Path;
use std::ffi::OsStr;Create a Path¶
let path = Path::new("./foo/bar.txt");
path"./foo/bar.txt"Path.file_stem¶
path.file_stem()Some("bar")path.file_stem() == Some(OsStr::new("bar"))truepath.file_stem() == Some(String::from("bar"))path.file_stem() == Some(String::from("bar"))
^^^^^^^^^^^^^^^^^^^ expected `&OsStr`, found struct `String`
mismatched typespath.extension(&self) -> Option<&OsStr>¶
Extracts the extension of self.file_name, if possible.
Notice that this method returns Option<&OsStr> instead of Option<&str>.
let path = Path::new("./foo/bar.txt");
path.extension()Some("txt")let path = Path::new("./foo/bar.txt");
path.extension() == Some(OsStr::new("txt"))truePath.exists¶
path.exists()falsePath::new("test.txt").exists()truePath.is_file¶
path.is_file()falsePath::new("test.txt").is_file()truePath.iter¶
Produces an iterator over the path’s components viewed as OsStr slices.
Note: This function does not get the content of a directory!
To get the content of a directory,
use the function Path.read_dir.
Path::new(".").canonicalize()Ok("/workdir/archives/blog/misc/content/2021/05/rust-Path")Path::new(".").canonicalize().unwrap().components()Components([RootDir, Normal("workdir"), Normal("archives"), Normal("blog"), Normal("misc"), Normal("content"), Normal("2021"), Normal("05"), Normal("rust-Path")])Path::new(".").canonicalize().unwrap().iter().for_each(|comp| {
println!("{:?}", comp);
});"/"
"workdir"
"archives"
"blog"
"misc"
"content"
"2021"
"05"
"rust-Path"
Path.parent¶
path.parent()Some("./foo")Path.read_dir¶
Path::new(".").read_dir().unwrap().for_each(|entry| {
if let Ok(entry) = entry {
println!("{:?}", entry.path());
}
});"./rust-Path.ipynb"
"./test.txt"
"./.ipynb_checkpoints"