【问题标题】:How do I get the previous second folder or the folder with a certian name如何获取前第二个文件夹或具有特定名称的文件夹
【发布时间】:2022-01-22 05:35:20
【问题描述】:

我想获取某个文件夹,这个文件夹的名字是'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/'

【问题讨论】:

    标签: python directory path pathlib


    【解决方案1】:

    你可以得到它

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-23
      • 2012-10-13
      • 2021-10-14
      • 1970-01-01
      • 2013-04-19
      • 1970-01-01
      • 2014-04-25
      相关资源
      最近更新 更多