在Python中提取一部分文件路径(目录) [英] Extract a part of the filepath (a directory) in 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
我正在使用 directory_i_need $ c来修改文件的内容$ c>名称(而不是路径)。我创建了一个函数,该函数将给我所有文件的列表,然后...
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.
我该怎么办?
推荐答案
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屋!
查看全文