且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Python中创建一个树形目录列表

更新时间:2023-11-30 14:34:22

尝试以下操作:

pre $ for path,dirs,os.walk中的文件(。):
打印路径
用于文件中的文件s:
print os.path.join(path,file)

你不需要从 dirs 打印条目,因为当你走路径的时候每个目录都会被访问,所以你稍后用打印路径


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()

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.