如何在 Rust 中列出目录的文件?

如何在 Rust 中列出目录中的所有文件?我正在寻找与下面的 Python 代码等价的代码。

files = os.listdir('./')
80056 次浏览

You could also use glob, which is expressly for this purpose.

extern crate glob;
use self::glob::glob;


let files:Vec<Path> = glob("*").collect();

Use std::fs::read_dir(). Here's an example:

use std::fs;


fn main() {
let paths = fs::read_dir("./").unwrap();


for path in paths {
println!("Name: {}", path.unwrap().path().display())
}
}

It will simply iterate over the files and print out their names.

This can be done with glob. Try this on the playground:

extern crate glob;
use glob::glob;
fn main() {
for e in glob("../*").expect("Failed to read glob pattern") {
println!("{}", e.unwrap().display());
}
}

You may see the source.


And for walking directories recursively, you can use the walkdir crate (Playground):

extern crate walkdir;
use walkdir::WalkDir;
fn main() {
for e in WalkDir::new(".").into_iter().filter_map(|e| e.ok()) {
if e.metadata().unwrap().is_file() {
println!("{}", e.path().display());
}
}
}

See also the Directory Traversal section of The Rust Cookbook.