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

后端 未结 7 1954
佛祖请我去吃肉
佛祖请我去吃肉 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:54

    In Python 3.4 you can use the pathlib module:

    >>> from pathlib import Path
    >>> p = Path('C:\Program Files\Internet Explorer\iexplore.exe')
    >>> p.name
    'iexplore.exe'
    >>> p.suffix
    '.exe'
    >>> p.root
    '\\'
    >>> p.parts
    ('C:\\', 'Program Files', 'Internet Explorer', 'iexplore.exe')
    >>> p.relative_to('C:\Program Files')
    WindowsPath('Internet Explorer/iexplore.exe')
    >>> p.exists()
    True
    

提交回复
热议问题