How do I get a file's parent directory?

前端 未结 4 1157
时光取名叫无心
时光取名叫无心 2021-01-11 17:40

Given a path to a file, c:\\xxx\\abc\\xyz\\fileName.jpg, how can I get the file\'s parent folder? In this example, I\'m looking for xyz. The number

4条回答
  •  误落风尘
    2021-01-11 17:49

    Using python >= 3.4 pathlib is part of the standard library, you can get the parent name with .parent.name:

    from pathlib import Path
    print(Path(path).parent.name)
    

    To get all the names use .parents:

    print([p.name for p in Path(path).parents])
    

    It can be installed for python2 with pip install pathlib

提交回复
热议问题