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

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

    First, see if you have splitunc() as an available function within os.path. The first item returned should be what you want... but I am on Linux and I do not have this function when I import os and try to use it.

    Otherwise, one semi-ugly way that gets the job done is to use:

    >>> pathname = "\\C:\\mystuff\\project\\file.py"
    >>> pathname
    '\\C:\\mystuff\\project\\file.py'
    >>> print pathname
    \C:\mystuff\project\file.py
    >>> "\\".join(pathname.split('\\')[:-2])
    '\\C:\\mystuff'
    >>> "\\".join(pathname.split('\\')[:-1])
    '\\C:\\mystuff\\project'
    

    which shows retrieving the directory just above the file, and the directory just above that.

    0 讨论(0)
提交回复
热议问题