is there a way to get one level above or below directory from the one that is given? For example '/a/b/c/' directory was entered in a function.
So function would return:
lvl_down = '/a/b/'
lvl_up = '/a/b/c/d/'
I think you can do it using 're' module (at least with one level below directory), but maybe there is more simple and better way to do it without regex?
I have no idea, how the function should know, that you want to go in directory d:
#!/usr/bin/python
import os.path
def lvl_down(path):
return os.path.split(path)[0]
def lvl_up(path, up_dir):
return os.path.join(path, up_dir)
print(lvl_down('a/b/c')) # prints a/b
print(lvl_up('a/b/c','d')) # prints a/b/c/d
Note: Had another solution before, but os.path is a much better one.
Methods for manipulating paths can be found in the modules os
and os.path
.
os.path.join - Join one or more path components intelligently.
os.path.split - Split the pathname path into a pair, (head, tail)
where tail is the last pathname component and head is everything leading up to that.
os.path.isdir - Return True if path is an existing directory.
os.listdir - Return a list containing the names of the entries in the directory given by path.
def parentDir(dir):
return os.path.split(dir)[0]
def childDirs(dir):
possibleChildren = [os.path.join(dir, file) for file in os.listdir(dir)]
return [file for file in possibleChildren if os.path.isdir(file)]
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