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. :)
Use File 's getParentFile() method and String. lastIndexOf() to retrieve just the immediate parent directory.
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.
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With