[英]How do I get the previous second folder or the folder with a certian name
我想獲取某個文件夾,這個文件夾的名稱是“ 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])
我得到了什么
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}"
我想要的是
'C:/Documents/something/certainName/'
你可以通過
from pathlib import Path
myFolder = 'certainName'
myPath = r'C:/Documents/something/certainName/anotherFolder/folder'
p = Path(myPath)
print(p.parent.parent)
或者
myFolder = 'certainName'
myPath = r'C:/Documents/something/certainName/anotherFolder/folder'
print('/'.join(myPath.split('/')[:-2]))
print(myPath.rsplit('/', maxsplit=2)[0])
他們都得到了
C:/Documents/something/certainName
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.