在 Python 中提取文件路径(目录)的一部分 [英] Extract a part of the filepath (a directory) in Python

查看:25
本文介绍了在 Python 中提取文件路径(目录)的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to extract the name of the parent directory of a certain path. This is what it looks like:

C:stuffdirectory_i_needsubdirfile.jpg

我想提取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
...

并且您可以根据需要继续多次执行此操作...

And you can continue doing this as many times as necessary...

来自os.path,您可以使用 os.path.split 或 os.path.basename:

from os.path, you can use either os.path.split or 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.

这篇关于在 Python 中提取文件路径(目录)的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆