Mil*_*sen 5 python filesystems
我试图用python列出目录和文件(recursivley):
./rootdir
./file1.html
./subdir1
./file2.html
./file3.html
./subdir2
./file4.html
Run Code Online (Sandbox Code Playgroud)
现在我可以很好地列出目录和文件(从这里借用它).但我想用以下格式和ORDER列出它(这对我正在做的事情非常重要.
/rootdir/
/rootdir/file1.html
/rootdir/subdir1/
/rootdir/subdir1/file2.html
/rootdir/subdir1/file3.html
/rootdir/subdir2/
/rootdir/file4.html
Run Code Online (Sandbox Code Playgroud)
我不在乎它是如何完成的.如果我走在目录中,然后组织它或按顺序获取所有内容.无论哪种方式,提前谢谢!
编辑:添加以下代码.
# 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()
Run Code Online (Sandbox Code Playgroud)
请尝试以下方法:
for path, dirs, files in os.walk("."):
print path
for file in files:
print os.path.join(path, file)
Run Code Online (Sandbox Code Playgroud)
您不需要打印条目,dirs因为在您走路径时将访问每个目录,因此您稍后将使用它打印print path.
| 归档时间: |
|
| 查看次数: |
4219 次 |
| 最近记录: |