gpt4 book ai didi

python - 如何解析相对于任何目录的相对路径

转载 作者:行者123 更新时间:2023-12-05 06:23:19 25 4
gpt4 key购买 nike

我知道如何将相对路径(如 '..\input\file\hello.txt')解析为相对于当前工作目录的绝对路径:

from pathlib import Path

rel_path = Path(r'..\input\file\hello.txt')
print(f'Absolute path: {rel_path.absolute()}'

cwdC:\project\source\时输出:

C:\project\source\..\input\file\hello.txt

而且我还知道使用 .resolve() 来完全解析间接寻址:

from pathlib import Path

rel_path = Path(r'..\input\file\hello.txt')
print(f'Resolved path: {rel_path.resolve()}'

cwdC:\project\source\时输出:

C:\project\input\file\hello.txt

如何在不更改当前工作目录(如果有的话)的情况下解析相对于任何路径的路径?甚至当我必须更改当前工作目录时,我如何才能完全解析一个实际上不存在的路径? (因为 .resolve() 仅适用于现有对象)

例如,使用虚构的get_relative_to():

get_relative_to(r'..\input\file\hello.txt', r'X:\bogus\folder')

理想情况下会返回 'X:\bogus\input\file\hello.txt'

最佳答案

从 3.6 版开始 resolve有一个参数strict,当strict=False时,即使路径不存在也可以解析。在 3.8.0 中测试的示例:

from pathlib import Path


def get_relative_to(path1, path2):
return (path2 / path1).resolve(strict=False)


print(
get_relative_to(
Path(r'..\input\file\hello.txt'),
Path(r'X:\bogus\folder'),
)
)

# X:\bogus\input\file\hello.txt

关于python - 如何解析相对于任何目录的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58499720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com