更新时间:2023-02-21 14:41:51
使用 os.path.dirname
获取目录路径.如果你只想要目录的名字,你可以使用 os.path.basename
从中提取基本名称:
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 of directories to get to the file may vary.
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'