How to get upper paths from a single path?

How to get upper paths from a single path?

So say you have a path like:

'C:\a\b\c\d\'

How do I get to 'C:\a\b' or 'C:\a\b\c'

Is there a pythonic way to do this?


Asked by: Sam362 | Posted: 06-12-2021






Answer 1

See os.path

from os import path
path.dirname("C:\\a\\b\\c\\d\\")

Answered by: Emily272 | Posted: 07-01-2022



Answer 2

Theres basic stuff like os.path methods.

If you want a list of the full path names of each successive parent in the directory tree, heres a one liner:

from os.path import dirname

def f1(n): return [n] if n == dirname(n) else [n] + f1(dirname(n))

print f1("/a/b/c/d/e/f/g")

Answered by: Julian979 | Posted: 07-01-2022



Answer 3

os.path.split("C:\\a\\b\\c") will return a tuple:

('C:\a\b', 'c')

You can continue to call split on the first element of the tuple.

Answered by: Edgar716 | Posted: 07-01-2022



Answer 4

>>> def go_up(path, n):
...     return os.path.abspath(os.path.join(*([path] + ['..']*n)))
>>> path = 'C:\\a\\b\\c\\d\\'
>>> go_up(path, 2)
'C:\\a\\b'
>>> go_up(path, 1)
'C:\\a\\b\\c'
>>> go_up(path, 0)
'C:\\a\\b\\c\\d'

Not being a regular user of os.path, I don't know if this is an appropriate/pythonic solution. I compared it to an alternate function, define as follows:

def go_up_2(path, n):
    for i in xrange(n):
        path = os.path.split(path)[0]
    return path

The first thing to note is that go_up_2('C:\\a\\b\\', 1) != go_up_2('c:\\a\\b', 1), where it does with the original go_up. However, performance is significantly better, if that is an issue (probably not, but I was looking for some definitive way to say my own algorithm was better):

import timeit

g1 = """import os.path
import ntpath
os.path = ntpath
def go_up(path, n):
    return os.path.abspath(os.path.join(*([path] + ['..']*n)))"""

g2 = """import os.path
import ntpath
os.path = ntpath
def go_up(path, n):
    for i in xrange(n-1):
        path = os.path.split(path)[0]
    return path"""

t1 = timeit.Timer("go_up('C:\\a\\b\\c\\d', 3)", setup=g1).timeit()
t2 = timeit.Timer("go_up('C:\\a\\b\\c\\d', 3)", setup=g2).timeit()

print t1
print t2

This outputs (on my machine):

133.364659071
30.101334095

Not very useful information, but I was playing around, and figured it should be posted here anyway.

Answered by: Elise839 | Posted: 07-01-2022



Similar questions

python - Limit a single record in model for django app?

I want use a model to save the system setting for a django app, So I want to limit the model can only have one record, how to do the limit?


python - Single player 'pong' game

I am just starting out learning pygame and livewires, and I'm trying to make a single-player pong game, where you just hit the ball, and it bounces around until it passes your paddle (located on the left side of the screen and controlled by the mouse), which makes you lose. I have the basic code, but the ball doesn't stay on the screen, it just flickers and doesn't remain constant. Also, the paddle does not move with the m...


python - How do I merge a list of dicts into a single dict?

How can I turn a list of dicts like [{'a':1}, {'b':2}, {'c':1}, {'d':2}], into a single dict like {'a':1, 'b':2, 'c':1, 'd':2}? Answers here will overwrite keys that match between two of the input dicts, because a dict cannot have duplicate keys. If you want to collect multiple values from matching keys, see


python - How to put a single column item into a single row?

I have a file like this: a b c d e f g h and so on, with a single word/number on each line. and after 4/5 lines a couple of ( or three ) space. what I want to do is put them like this a,b,c,d e,f,g,h I was working with sed, but sed is oneliner and seems to helpless for the addition of multiple lines. Can anybody help me with a shell script? I know this ...


Python - Parse Single Line from XML

Hopefully this is a quick answer for those experienced. I have a single XML file that contains a URL in it, I'd like to take the URL from the XML and then input it into a downloader script I've written. My only issue is I can't seem to properly parse JUST the url from the XML. This is what it looks like: <program new-version="1.1.1.1" name="ProgramName"> <download-url value="http://website.com/file...


python - Single Sign On in Django

Regards I,m workig in a django development with at least 4 apps, where every app have is own domain, the idea is centralize a Single Sign On to this 4 apps with a central db and central login panel, when a user login in the main login panel could be redirect to any of the other apps without login again. Also I need when the user logout, the logout works for all apps. I have been res...


python - How to look for a single value in a set of tuples?

Suppose I have this set: a = set([(1,2),(3,4),(5,6)]) How do I test if "3" or "7" can be found in that set?


python - Two lines of text in a single grid row

Does anybody know if it's possible to put two lines of text in a single row using grid in TKinter? If I make the font small enough, can I distribute the text in two lines?


python - Grab two parts of a single, short string

I'm looking to fill a python dict with TAG:definition pairs, and I'm using RegExr http://gskinner.com/RegExr/ to write the regex My first step is to parse a line, from http://www.id3.org/id3v2.3.0, or http://p...


python - Skip single loop

I'm looping over all lines in a file, splitting each line into tokens based on whitespace. For example, a line: circle 1 2 3 would be split into 4 tokens, circle, 1, 2, 3. If the line begins with a comment (#) or is empty, my tokenList is also empty. If this is the case, I can't check tokenList[0] etc. ...


python - What's the best Django search app?


How can I use a DLL file from Python?

What is the easiest way to use a DLL file from within Python? Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python? Native Python functionality is strongly preferred over using a third-party library.


python - PubSub lib for c#

Is there a c# library which provides similar functionality to the Python PubSub library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.


python - What is the best way to copy a list?

This question already has answers here:


python - Possible Google Riddle?

My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. t-shirt So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that eac...


How do you check whether a python method is bound or not?

Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?


ssh - How to scp in Python?

What's the most pythonic way to scp a file in Python? The only route I'm aware of is os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted'...


python - How do I create a new signal in pygtk

I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.


python - What do I need to import to gain access to my models?

I'd like to run a script to populate my database. I'd like to access it through the Django database API. The only problem is that I don't know what I would need to import to gain access to this. How can this be achieved?


python - How do I edit and delete data in Django?

I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete! Please show me an example of the code ...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top