Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parents directories of a file, up to a point

Tags:

python

If I have a path for a given file, say 'C:\Folder\OtherFolder\AnotherFolder\file.txt', is there a way in python I can get all the parent directories for file.txt up to 'OtherFolder'? The depth of the path is not constant, so I can't just iterate back a certain number of times, but I always need to get up to 'OtherFolder' regardless of depth. I feel like this should be easier than I'm making it, but they say Thursday is the new Monday. :)

like image 444
Jon Martin Avatar asked May 10 '12 14:05

Jon Martin


People also ask

How do I get the parent directory of a file?

Use File 's getParentFile() method and String. lastIndexOf() to retrieve just the immediate parent directory.

How do I reference a parent directory in Python?

Get the Parent Directory in Python Using the path. parent() Method of the pathlib Module. The path. parent() method, as the name suggests, returns the parent directory of the given path passed as an argument in the form of a string.

How do I get the directory of a file in Python?

In order to obtain the Current Working Directory in Python, use the os. getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.


1 Answers

If you are using Windows, try this:

import os
os.path.relpath('C:\Folder\OtherFolder\AnotherFolder\file.txt', 'C:\Folder\OtherFolder')

You can then split it using os.path.sep (in your case \):

rel_path.split(os.path.sep)

to get the individual directories.

On a Linux machine a similar call returns what you mean:

os.path.relpath('/Folder/OtherFolder/AnotherFolder/file.txt', '/Folder/OtherFolder')
# returns 'AnotherFolder/file.txt'

rel_path.split(os.path.sep)
# returns ['AnotherFolder', 'file.txt']
like image 78
eumiro Avatar answered Oct 31 '22 02:10

eumiro