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

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

c:\stuff\directory_i_need\subdir\file

I am modifying the content of the "file" with something that uses the directory_i_need name in it (not the path). I have created a function that will give me a list of all the files, and then...

for path in file_list:

#directory_name = os.path.dirname(path) # this is not what I need, that's why it is commented

directories, files = path.split('\\')

line_replace_add_directory = line_replace + directories

# this is what I want to add in the text, with the directory name at the end

# of the line.

How can I do that?

解决方案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...

Edit: 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值