isar
isar

Reputation: 1791

Convert path to list

I have a path made of directories (e.g. 'grandpa\\parent\\child') that I need to transform in a list (e.g. ['grandpa', 'parent', 'child']).

The path can have less or more subdirectories (e.g. ['parent', 'child']).

I tried iterating os.path.split() but it doesn't work well in all circumstances:

import os

s = []
def splitall(path):
    l = list(os.path.split(path))
    s.append(l[1])
    return s if l[0] == '' else splitall(l[0])

p = 'grandpa\\parent\\child'
l = splitall(p)
print(l)

There should be a better way, right? Maybe a method that I'm not aware of.

Upvotes: 0

Views: 2035

Answers (1)

Adam Smith
Adam Smith

Reputation: 54163

You can use pathlib too.

import pathlib

path = "a\\b\\c"
p = pathlib.Path(path)
result = p.parts

Upvotes: 6

Related Questions