【发布时间】:2014-09-27 15:04:07
【问题描述】:
如何在 Rust 中列出一个目录的所有文件?我正在寻找以下 Python 代码的等价物。
files = os.listdir('./')
【问题讨论】:
-
std::io::fs::readdir
标签: rust
如何在 Rust 中列出一个目录的所有文件?我正在寻找以下 Python 代码的等价物。
files = os.listdir('./')
【问题讨论】:
std::io::fs::readdir
标签: rust
使用std::fs::read_dir()。这里是an example:
use std::fs;
fn main() {
let paths = fs::read_dir("./").unwrap();
for path in paths {
println!("Name: {}", path.unwrap().path().display())
}
}
它将简单地遍历文件并打印出它们的名称。
【讨论】:
您也可以使用glob,它专门用于此目的。
extern crate glob;
use self::glob::glob;
let files:Vec<Path> = glob("*").collect();
【讨论】:
the trait bound `[u8]: std::marker::Sized` is not satisfied in `std::path::Path` (within `std::path::Path`, the trait `std::marker::Sized` is not implemented for `[u8]`) [E0277] `[u8]` does not have a constant size known at compile-time [E0277] required because it appears within the type `std::path::Path` [E0277] required by `std::vec::Vec` [E0277]
这可以通过glob 完成。试试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());
}
}
您可能会看到source。
对于递归遍历目录,您可以使用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());
}
}
}
另请参阅 The Rust Cookbook 的 Directory Traversal 部分。
【讨论】: