简体   繁体   English

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

[英]Python3 - Shorten path for home directory in Ubuntu

What I have is a path of a file which is in the home directory, and I wish to process it to become shorten path which includes "~" in it.我所拥有的是主目录中的文件路径,我希望将其处理为包含“~”的缩短路径。

For example, my input could be:例如,我的输入可能是:

"/home/username/test" or /home/./username/test or /home/../home/username/test "/home/username/test"/home/./username/test/home/../home/username/test

and I wish to get我希望得到

~/test

I tried to .split("/") and match the first 2 terms, but when it's a little more complicated with all those "."我尝试.split("/")并匹配前两个术语,但是当所有这些“。”有点复杂时。 and ".." I have no idea how to achieve this.和“..”我不知道如何实现这一点。

How do I process paths in an efficient way to achieve the above goal?如何以有效的方式处理路径以实现上述目标?

Useos.path.realpath to convert a path to canonical form and then check if the beginning is the same as a home directory.使用os.path.realpath将路径转换为规范形式,然后检查开头是否与主目录相同。

Try to use尝试使用

from pathlib import Path
home_path = str(Path.home())

Here is the documentation link这是文档链接

Thanks for all the help!感谢所有的帮助!

My final solution using os.path.realpath() is as follow我使用os.path.realpath()的最终解决方案如下

Please comment if I have done something wrong or if there is a better way!如果我做错了什么或有更好的方法,请发表评论!

from os import path

def getShortPath(p):
    realpath = path.realpath(p).split("/")[1:]
    homepath = path.expanduser("~").split("/")[1:]
    if realpath[:2] == homepath:
        processed = "~"
        realpath = realpath[2:]
    else: processed = "/"
    for i in realpath:
        processed = path.join(processed,i)
    return processed

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

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