gpt4 book ai didi

Python3 - 缩短 Ubuntu 中主目录的路径

转载 作者:行者123 更新时间:2023-12-04 18:59:56 27 4
gpt4 key购买 nike

我所拥有的是主目录中的文件路径,我希望将其处理为包含“~”的缩短路径。
例如,我的输入可能是:"/home/username/test"/home/./username/test/home/../home/username/test我希望得到~/test我试过 .split("/")并匹配前两个术语,但是当所有这些“。”有点复杂时和“..”我不知道如何实现这一点。
如何以有效的方式处理路径以实现上述目标?

最佳答案

使用os.path.realpath将路径转换为规范形式,然后检查开头是否与主目录相同。

关于Python3 - 缩短 Ubuntu 中主目录的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63234890/

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