简体   繁体   English

带有 pathlib 的路径部分列表中的路径

[英]Path from list of path parts with pathlib

I want to generate a path based on a list inside the configuration toml.我想根据配置 toml 中的列表生成路径。 I have chosen a list to be able to support different operating systems.我选择了一个能够支持不同操作系统的列表。

For example the following list is stored inside my configuration.toml:例如,以下列表存储在我的 configuration.toml 中:

temporary_storage_folder = ["~", "temp", "machine_name"]

This should then be converted into a Path object.然后应将其转换为路径 object。

The trivial constructor seems not to exists, so:平凡的构造函数似乎不存在,所以:

from pathlib import Path
Path(["~", "temp", "mesomics"])

does not work.不起作用。

I came up with the following solution我想出了以下解决方案

from pathlib import Path
config_list = ["~", "temp", "machine_name"] # is actually parsed from the toml
path_list = [Path(x) for x in config_list]
path_obj = Path(*path_list)

but I'm not sure if this is best practice or the pythonic way of achieving my goal.但我不确定这是实现我目标的最佳实践还是 pythonic 方式。 I'm also open to suggestions on how to otherwise save a general path in a config.我也乐于接受有关如何在配置中保存通用路径的建议。

You can just do:你可以这样做:

from pathlib import Path
config_list = ["~", "temp", "machine_name"] 
storage_obj = Path(*config_list)

Which generates:其中产生:

PosixPath('~/temp/machine_name')

In terms of specific usage for config files, I would use Pydantic with a Path field:就配置文件的具体用法而言,我会使用 Pydantic 和 Path 字段:

from pydantic import BaseSettings
import pathlib

class SetupConfig(BaseSettings):
    path_obj: pathlib.Path

Then you can add your own validators to ensure the path is valid (such as, if it actually exists and the path is a directory and the directory has the correct stuff within it)然后您可以添加自己的验证器以确保路径有效(例如,如果它确实存在并且路径是一个目录并且该目录中包含正确的内容)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM