规范化不存在的路径

规范化不存在的路径

本文介绍了仅使用 pathlib 规范化不存在的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python 最近添加了 pathlib 模块(我非常喜欢它!).

python has recently added the pathlib module (which i like a lot!).

我只有一件事正在苦苦挣扎:是否可以将不存在的文件或目录的路径规范化?我可以用 os.path.normpath 很好地做到这一点.但是不得不使用应该处理路径相关内容的库以外的东西不是很荒谬吗?

there is just one thing i'm struggling with: is it possible to normalize a path to a file or directory that does not exist? i can do that perfectly well with os.path.normpath. but wouldn't it be absurd to have to use something other than the library that should take care of path related stuff?

我想要的功能是:

from os.path import normpath
from pathlib import Path
pth = Path('/tmp/some_directory/../i_do_not_exist.txt')
pth = Path(normpath(str(pth)))
# -> /tmp/i_do_not_exist.txt

但不必求助于os.path,也不必将类型转换为str 并返回到Path.pth.resolve() 也不适用于不存在的文件.

but without having to resort to os.path and without having to type-cast to str and back to Path. also pth.resolve() does not work for non-existing files.

是否有一种简单的方法可以仅使用 pathlib 来做到这一点?

is there a simple way to do that with just pathlib?

推荐答案

从 3.6 开始,这是默认行为.请参阅 https://docs.python.org/3.6/library/pathlib.html#pathlib.Path.resolve

Starting from 3.6, it's the default behavior. See https://docs.python.org/3.6/library/pathlib.html#pathlib.Path.resolve

路径.解决(strict=False)
...
如果strictFalse,则尽可能解析路径,并附加任何剩余部分,不检查是否存在

这篇关于仅使用 pathlib 规范化不存在的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 15:24