简体   繁体   English

如何获取前第二个文件夹或具有特定名称的文件夹

[英]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.我想获取某个文件夹,这个文件夹的名称是“ certainName'或者是之前的两个文件夹。

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/'

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM