How do I pull last 3 levels from a file path in python?

I have a file path

filePath = "dir1/dir2/dir3/dir4/dir5/file.txt"

How do I pull the last 3 levels from the path? Output:

newFilePath = "dir4/dir5/file.txt"


You can use split and join to get the last n from some file path. For example,

test = "some/dir/somewhere/here/"
new = "/".join(i for i in test.split("/")[-4:])
print(new) # 'dir/somewhere/here/'

Previous : Javascript Is there a way that when I push data it doesn't show output the last line?
Next : Translate curl to Powershell Invoke-Restmethod