小编典典

在 Python 中提取文件路径(一个目录)的一部分

all

我需要提取某个路径的父目录的名称。这是它的样子:

C:\stuff\directory_i_need\subdir\file.jpg

我想提取directory_i_need.


阅读 59

收藏
2022-06-20

共1个答案

小编典典

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.
2022-06-20