home ~ projects ~ socials

Get A Filename From A Rust Path Without The Extension

TL;DR

Use file_stem() to get a filename from a path without its extensio

use std::path::PathBuf;

fn main() {
  let path = PathBuf::from("some/path/to/alfa.html");
  let file_name = path.file_stem().unwrap().to_string_lossy();
  println!("{}", file_name);
}
Output:
alfa

Notes

  • file_stem() gets the filename up until the last dot. That means if the input is something like alfa.tar.gz the output will be alfa.tar instead of alfa
  • There's a file_prefix() in nightly Rust that gets the name up until the first dot. (i.e. given alfa.tar.gz it will return alfa)
  • file_stem() returns an OsString. I'm converting it to a regular String here with to_string_lossy(). It makes sure that invalid UTF characters are replaced with a placeholder instead of breaking the string
-- end of line --

References