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

后端 未结 7 1977
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  猫巷女王i
    2020-12-07 17:56

    import os
    
    directory = os.path.abspath('\\') # root directory
    print(directory) # e.g. 'C:\'
    
    directory = os.path.abspath('.') # current directory
    print(directory) # e.g. 'C:\Users\User\Desktop'
    
    parent_directory, directory_name = os.path.split(directory)
    print(directory_name) # e.g. 'Desktop'
    parent_parent_directory, parent_directory_name = os.path.split(parent_directory)
    print(parent_directory_name) # e.g. 'User'
    

    This should also do the trick.

提交回复
热议问题