Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a tree-style directory listing in Python

I am trying to list directories and files (recursivley) in a directory with python:

./rootdir
  ./file1.html
  ./subdir1
    ./file2.html
    ./file3.html
  ./subdir2
  ./file4.html

Now I can list the directories and files just fine (borrowed it from here). But I would like to list it in the following format and ORDER (which is very important for what I am doing.

/rootdir/
/rootdir/file1.html
/rootdir/subdir1/
/rootdir/subdir1/file2.html
/rootdir/subdir1/file3.html
/rootdir/subdir2/
/rootdir/file4.html

I don't care how it gets done. If I walk the directory and then organize it or get everything in order. Either way, thanks in advance!

EDIT: Added code below.

# list books
import os
import sys

lstFiles = []
rootdir = "/srv/http/example/www/static/dev/library/books"

# Append the directories and files to a list
for path, dirs, files in os.walk(rootdir):
    #lstFiles.append(path + "/")
    lstFiles.append(path)
    for file in files:
        lstFiles.append(os.path.join(path, file))

# Open the file for writing
f = open("sidebar.html", "w")
f.write("<ul>")

for item in lstFiles:
    splitfile = os.path.split(item)
    webpyPath = splitfile[0].replace("/srv/http/example/www", "")
    itemName = splitfile[1]
    if item.endswith("/"):
        f.write('<li><a href=\"' + webpyPath + "/" + itemName + '\" id=\"directory\" alt=\"' + itemName + '\" target=\"viewer\">' + itemName + '</a></li>\n')
    else:
        f.write('<li><a href=\"' + webpyPath + "/" + itemName + '\" id=\"file\" alt=\"' + itemName + '\" target=\"viewer\">' + itemName + '</a></li>\n')

f.write("</ul>")
f.close()
like image 333
Milo Gertjejansen Avatar asked Sep 19 '11 23:09

Milo Gertjejansen


1 Answers

Try the following:

for path, dirs, files in os.walk("."):
    print path
    for file in files:
        print os.path.join(path, file)

You do not need to print entries from dirs because each directory will be visited as you walk the path, so you will print it later with print path.

like image 183
Andrew Clark Avatar answered Sep 30 '22 10:09

Andrew Clark