How do I get a file's parent directory?

前端 未结 4 1107
时光取名叫无心
时光取名叫无心 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

    Use os.path.dirname to get the directory path. If you only want the name of the directory, you can use os.path.basename to extract the base name from it:

    >>> path = r'c:\xxx\abc\xyz\fileName.jpg'
    >>> import os
    >>> os.path.dirname(path)
    'c:\\xxx\\abc\\xyz'
    >>> os.path.basename(os.path.dirname(path))
    'xyz'
    

提交回复
热议问题