[Tutor] turn a path into nested list

ingo ingoogni at gmail.com
Thu Jan 13 20:36:59 CET 2011


On Thu, Jan 13, 2011 at 6:30 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:

> Its not clear what exactly the sort criteria is,

sorry Alan, I meant that I want to keep the order as is.

> however have you looked
> at the os.walk() function for traversing directory trees? It may be all
> you need.

Yes, but I'm not confident with it (the more reason to use it you will say :) ).
Below the script I'm working on, rather unstable still. It will be put
to work in Cherrypy so I browse through my media directories and send
playlists to my media player(s). Very preliminary still.

ingo

--- %< --- %< ---
import os, string, urllib

topdirs={
    'Audio': 'c:',
    'Video': 'd:',
    'Photo': 'e:'
    }

path = 'c:\\Python27'
path = os.path.abspath(path)
print path

topdir = 'Audio'

def mkPATH(path, topdirs=topdirs):
    path=urllib.url2pathname(path)
    path=string.split(path,'\\',1)
    return os.path.join(topdirs[path[0]],path[1])

def mkURL(dir):
    return urllib.pathname2url(dir)

def mk_alias(dir, old=topdirs[topdir], new=topdir):
    return string.replace(dir,old,new)

def mk_aliasURL(dir):
    return mkURL(mk_alias(dir))

def mk_pathlist(path):
    pathlist=[]
    dir=''
    for item in path.split("\\"):
        dir=os.path.join(dir,item)
        dir=mkURL(dir)
        a=[item,dir]
        pathlist.append(a)
    return pathlist

aliaspath = mk_alias(path)

directories = mk_pathlist(aliaspath)
files = []

content = os.listdir(path)
content.sort()
for item in content:
    fullpath = os.path.join(path, item)
    if os.path.isdir(fullpath):
        directories.append([item, mk_aliasURL(fullpath)])
    else:
        files.append([item, mk_aliasURL(fullpath)])

print '\n Path \n', path
print '\n AliasPath \n', aliaspath
print '\n Dirs \n', directories
print '\n Files \n', files


More information about the Tutor mailing list