Search code examples
pythondirectorypathpathlib

How do I get the previous second folder or the folder with a certian name


I want to get a certain folder, the name of this is 'certainName' or it is two folder previous.

myFolder = 'certainName'
myPath = r'C:/Documents/something/certainName/anotherFolder/folder'

p = pathlib.Path(myPath)
print(p.relative_to(*p.parts[-2:]))

# Another way

folder = myPath.split(myFolder)
print(folder[0])

What I got

Traceback (most recent call last):
  File "model.py", line 26, in <module>
    getPrice(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]))
  File "model.py", line 11, in getPrice
    print(p.relative_to(*p.parts[-2:]))
  File "C:\Users\user\anaconda3\lib\pathlib.py", line 907, in relative_to
    raise ValueError("{!r} does not start with {!r}"

What I want

'C:/Documents/something/certainName/'

Solution

  • You can got it by

    from pathlib import Path
    
    myFolder = 'certainName'
    myPath = r'C:/Documents/something/certainName/anotherFolder/folder'
    
    p = Path(myPath)
    print(p.parent.parent)
    

    or

    myFolder = 'certainName'
    myPath = r'C:/Documents/something/certainName/anotherFolder/folder'
    
    print('/'.join(myPath.split('/')[:-2]))
    print(myPath.rsplit('/', maxsplit=2)[0])
    

    All of them got

    C:/Documents/something/certainName