我试图用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()
尝试以下操作:
您不需要打印
dirs
中的条目,因为在您走过路径时,每个目录都会被访问,所以您稍后将使用print path
打印它。在相关问题 更多 >
编程相关推荐