Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - change given directory one level above or below [closed]

Tags:

python

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?

like image 546
Andrius Avatar asked Dec 16 '22 17:12

Andrius


2 Answers

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.

like image 72
Sebastian Werk Avatar answered Jan 25 '23 22:01

Sebastian Werk


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)]
like image 40
Kevin Avatar answered Jan 25 '23 22:01

Kevin