在Python中创建一个treestyle目录列表

2024-06-30 08:28:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python列出目录和文件(recursivley):

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

现在我可以很好地列出目录和文件(从here借用)。但我想按以下格式和顺序列出(这对我正在做的事情非常重要)。在

^{pr2}$

我不管怎么做。如果我浏览目录然后整理它或者把所有的东西都整理好。不管怎样,先谢谢你!在

编辑:在下面添加代码。在

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

Tags: pathin目录foroshtmlfilesli
1条回答
网友
1楼 · 发布于 2024-06-30 08:28:37

尝试以下操作:

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

您不需要打印dirs中的条目,因为在您走过路径时,每个目录都会被访问,所以您稍后将使用print path打印它。在

相关问题 更多 >