How to `glob` on `PathBuf`/`Path`

I am coming from Python. It has a very convenient method in its standard library pathlib to search for a file by pattern for a given Path. e.g.,

>>> from pathlib import Path
>>> p = Path("C:\ProgramData")
>>> list(p.glob("**/mpc*.exe"))
[WindowsPath('C:/ProgramData/Microsoft/Windows Defender/Platform/4.18.2110.6-0/MpCmdRun.exe'), WindowsPath('C:/ProgramData/Microsoft/Windows Defender/Platform/4.18.2110.6-0/MpCopyAccelerator.exe'), WindowsPath('C:/ProgramData/Microsoft/Windows Defender/Platform/4.18.2110.6-0/X86/MpCmdRun.exe'), WindowsPath('C:/ProgramData/Microsoft/Windows Defender/Platform/4.18.2111.5-0/MpCmdRun.exe'), WindowsPath('C:/ProgramData/Microsoft/Windows Defender/Platform/4.18.2111.5-0/MpCopyAccelerator.exe'), WindowsPath('C:/ProgramData/Microsoft/Windows Defender/Platform/4.18.2111.5-0/X86/MpCmdRun.exe')]

In rust, I have (writing from memory)

let p = PathBuf::from("C:\ProgramData"); 
/// p.glob("**/mpc*.exe")  // some magical crate? 

There is crate glob (glob - Rust) which I can use if nothing exists that work directly on PathBuf. glob::glob takes &str as argument.

There's no standard glob functionality, that's why the glob crate exists. You can convert a path to a String using the to_str() or to_string_lossy() methods, depending on how you are planning to handle invalid Unicode, and feed the resulting string to glob.

There's also the crate globset, its is_match function can take Paths as input directly without converting to utf-8.

I ended up using WalkDir in walkdir - Rust that worked really well with Path. I could not get glob to work as expected: probably because Path::to_lossy_string() adds \\ to its output while glob seems to work only with /.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.