Extract a part of the filepath (a directory) in Python

后端 未结 7 1978
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-07 17:10

I need to extract the name of the parent directory of a certain path. This is what it looks like:

c:\\stuff\\directory_i_need\\subdir\\file
<
7条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 17:47

    All you need is parent part if you use pathlib.

    from pathlib import Path
    p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
    print(p.parent) 
    

    Will output:

    C:\Program Files\Internet Explorer    
    

    Case you need all parts (already covered in other answers) use parts:

    p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
    print(p.parts) 
    

    Then you will get a list:

    ('C:\\', 'Program Files', 'Internet Explorer', 'iexplore.exe')
    

    Saves tone of time.

提交回复
热议问题