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?
You have to put the entire path as a parameter to os.path.split. See The docs. It doesn't work like string split.
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:
In Python 3.4 you can use the pathlib module:
First, see if you have
splitunc()
as an available function withinos.path
. The first item returned should be what you want... but I am on Linux and I do not have this function when I importos
and try to use it.Otherwise, one semi-ugly way that gets the job done is to use:
which shows retrieving the directory just above the file, and the directory just above that.
This is what I did to extract the piece of the directory:
Thank you for your help.