How can I list files of a directory in Rust?

后端 未结 3 635
一整个雨季
一整个雨季 2021-02-04 23:21

How can I list all the files of a directory in Rust? I am looking for the equivalent of the following Python code.

files = os.listdir(\'./\')
3条回答
  •  星月不相逢
    2021-02-05 00:07

    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.

提交回复
热议问题