How to walk up parent directories?

M

Matthew Wilson

Is there already a tool in the standard library to let me walk up from a
subdirectory to the top of my file system?

In other words, I'm looking for something like:
... print(x)
/home/matt/projects
/home/matt
/home
/

I know I could build something like this with various os.path
components, but I'm hoping I don't have to.

TIA


Matt
 
S

Snorri H

Is there already a tool in the standard library to let me walk up from a
subdirectory to the top of my file system?


Never seen such a standard tool, yet it can be implemented in a way
like this

def walkup(path):
aux = path.rsplit('/')
while aux != ['']:
yield reduce(lambda x,y:x+'/'+y,aux)
aux.pop()
yield '/'

Maybe this is not the best way to ascend directories, but it seems to
work.
 
D

Diez B. Roggisch

Snorri said:
Is there already a tool in the standard library to let me walk up from a
subdirectory to the top of my file system?


Never seen such a standard tool, yet it can be implemented in a way
like this

def walkup(path):
aux = path.rsplit('/')
while aux != ['']:
yield reduce(lambda x,y:x+'/'+y,aux)
aux.pop()
yield '/'

Maybe this is not the best way to ascend directories, but it seems to
work.

It's not working for windows. And using reduce to create a path instead of

os.sep.join(aux)

seems to be showing off mad functional coding skillz than anything else...

Diez
 
D

David Smith

Matthew said:
Is there already a tool in the standard library to let me walk up from a
subdirectory to the top of my file system?

In other words, I'm looking for something like:

... print(x)
/home/matt/projects
/home/matt
/home
/

I know I could build something like this with various os.path
components, but I'm hoping I don't have to.

TIA


Matt

You should take a look at the os.path module. Seems like you might find
something in that toolbox for this.

--David
 
M

Matthew Wilson

Not every simple function belongs in the standard library :)

Thanks for the help with this! Maybe I'm overestimating how often
people need this walkup function.

Matt
 
D

Dave Angel

Matthew said:
Thanks for the help with this! Maybe I'm overestimating how often
people need this walkup function.

Matt
Look at os.path.normpath(os.path.join( name, ".."))
 
G

Gunter Henriksen

Be careful not to presume "/a/b/" is the same directory as "/a/b/c/../"
I would consider the latter the parent of /a/b/c/, not the former.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,434
Messages
2,571,691
Members
48,796
Latest member
Greg L.

Latest Threads

Top