Search code examples
pythonglob

How can I get the pathname of the folder two directories upstream of a file?


Using glob2 and os I would like the directory '/a/b/' given the file path '/a/b/c/xyz.txt'

I have been able to (recursively) move forward through directories using /* and /** in glob2, but not backwards through parent directories. I don't want to use regular expressions or split. Is there a simple way to do this using glob and/or os?


Solution

  • Why glob?

    dir_path = file_path.split('/')
    what_i_want = '/' + dir_path[10] + '/' + dir_path[1] + '/'
    

    You can also do this by finding the index of the 3rd slash, using the return of each call as the "start" argument to the next.

    third_slash = file_path.index('/', file_path.index('/', file_path.index('/')+1) +1)
    what_i_want = file_path[:third_slash+1]