rust - 从 glob-entry 获取文件路径以用于 fs::read_to_string

标签 rust glob

我读了一个带有 glob 的目录。我可以打印文件路径,但我无法将路径作为字符串获取以在 fs::read_to_string()

中使用它
extern crate glob;

use glob::glob;
use std::fs;

fn main() {
    let source_files_glob = "/my/sample/path/*.ext";

    for entry in glob(source_files_glob).expect("Failed to read glob pattern") {
        println!("{}", entry.unwrap().display());

        let file_content = fs::read_to_string(entry.unwrap().display()).expect("Something went wrong reading the file");

        println!("Content: {}", file_content);
    }
}

我遇到了这个错误:

  --> src/main.rs:12:28
   |
12 |         let file_content = fs::read_to_string(entry.unwrap().display()).expect("Something went wrong reading the file");
   |                            ^^^^^^^^^^^^^^^^^^ the trait `std::convert::AsRef<std::path::Path>` is not implemented for `std::path::Display<'_>`
   |

如何从条目中获取完整的文件路径以在“fs::read_to_string”中使用它?

最佳答案

您不需要像 std::fs::read_to_string 这样的字符串需要 AsRef<Path>作为参数。

您应该简单地使用条目的 OK值,这是一个 Path :

let file_content = fs::read_to_string(entry.unwrap()).expect("...");

请注意,干净的程序通常会处理错误:

for entry in glob(source_files_glob).expect("Failed to read glob pattern") {
    match entry {
        OK(path) => {
            println!("{}", path.display());
            let file_content = fs::read_to_string(path).expect("...");
            println!("Content: {}", file_content);
        }
        Err(e) => {
            // handle error
        }
    }
}

关于rust - 从 glob-entry 获取文件路径以用于 fs::read_to_string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57690855/

相关文章:

json - 使用 Serde 将两种类型转换为一种类型

rust - 在Vulkan计算管道中使用输入和输出缓冲区

syntax - 什么是最直接的链接比较方法,产生第一个不相等的?

python - os.walk 还是 glob 更快?

rust - 如何从枚举返回内部类型变量引用而又没有遍历泛型?

rust - rusqlite和pyo3 PyResult处理错误

如果文件包含 $_GET[number],PHP 显示可供下载的文件

git - 为什么带有双星号的 glob 模式与子目录中的任何内容都不匹配?

python-3.x - 如何从 Pathlib glob ('**' 中排除隐藏目录)

python - 如何在 python 中找到系统上的目录,无论它位于何处?