我需要提取某个路径的父目录的名称。这是它的样子:
C:\stuff\directory_i_need\subdir\file.jpg
我想提取directory_i_need.
directory_i_need
import os ## first file in current dir (with full path) file = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0]) file os.path.dirname(file) ## directory of file os.path.dirname(os.path.dirname(file)) ## directory of directory of file ...
您可以根据需要继续执行此操作多次…
编辑: 从os.path,您可以使用 os.path.split 或 os.path.basename:
dir = os.path.dirname(os.path.dirname(file)) ## dir of dir of file ## once you're at the directory level you want, with the desired directory as the final path node: dirname1 = os.path.basename(dir) dirname2 = os.path.split(dir)[1] ## if you look at the documentation, this is exactly what os.path.basename does.