Getting the tail of a file path

I cannot find an effective way to do this. The best way to describe what I'm trying to do is an example, so when we go (assuming / bar / is the parent):

C:\foo\bar\baz\text.txt 

will be my way. I'm interested in everything up to the parent directory of the top level path. I need a script that does just that. In other words, I only want to capture

 \bar\baz\text.txt 

Split does not work for me. It will separate the file and the path, but it will not give the way out. Is there a built-in function that I am missing or am I SOL? Thanks!

+4
source share
7 answers

You can always use string.split() :

 >>> print '\\' + path.split('\\', 2)[-1] \bar\baz\text.txt 
+1
source

I'm not sure what you mean when you say "top level parent directory". Your top-level directory is C:\ . Parent of what? If you are trying to get a relative path that starts with the parent of the current working directory, try the following:

 import os.path os.path.relpath("C:\\foo\\bar\\baz\\text.txt", os.path.dirname(os.path.realpath('..'))) 
+1
source

Not sure what you want, but you can use the little-known rsplit, which splits on the right side of the line.

 >>> filepath = r"C:\foo\bar\baz\text.txt" >>> directories_deep = 3 >>> os.path.sep.join(filepath.rsplit(os.path.sep, directories_deep)[-directories_deep:]) 'bar\\baz\\text.txt' 
+1
source

I created a helper function that does the job:

 import os def get_path_tail(path, tail_length = 1): assert isinstance(tail_length, int) if tail_length == 1: return path.split('/')[-tail_length] elif tail_length > 1: return os.path.join(*path.split('/')[-tail_length:]) 

Behavior:

 >>> path = os.path.join('C:','foo','bar', 'baz','text.txt') >>> print get_path_tail(path, tail_length = 3) bar/baz/text.txt 

His signature is in ForeverWintr’s answer, but I couldn’t comment on his answer, because I don’t have enough reputation yet. :)

+1
source
 In [44]: path = 'a/b/c' In [45]: back = os.path.relpath('.', os.path.join(path, '..')) In [46]: back Out[46]: '..\\..' In [47]: tail = os.path.relpath(path, os.path.join(path, back))) In [48]: tail Out[48]: 'b\\c' 

Aka is not what I know.

0
source

I would keep it simple. Convert both cwd and your input path to absolute paths and then just use startswith and slicing

 path = os.path.abspath(path) #Make sure you finish curDir with a path separator #to avoid incorrect partial matches curDir = os.path.abspath(".") + os.path.sep if path.startswith(curDir): whatYouWant = path[len(curDir) - 1:] 
0
source

Here is how I solved this problem:

 def gettail(path_, length): elements = [] for i in range(length): s = os.path.split(path_) elements.append(s[1]) path_ = s[0] outpath = elements.pop() while elements: outpath = os.path.join(outpath, elements.pop()) return outpath 

Output:

 >>> print gettail(r"C:\foo\bar\baz\text.txt", 3) 'bar\\baz\\text.txt' 

Suggestions / improvements are welcome.

0
source

All Articles