我在使用Python生成html文档时遇到了一些问题.我正在尝试创建目录树的HTML列表.这是我到目前为止:
def list_files(startpath):
for root, dirs, files in os.walk(startpath):
level = root.replace(startpath, '').count(os.sep)
if level <= 1:
print('<li>{}<ul>'.format(os.path.basename(root)))
else:
print('<li>{}'.format(os.path.basename(root)))
for f in files:
last_file = len(files)-1
if f == files[last_file]:
print('<li>{}</li></ul>'.format(f))
elif f == files[0] and level-1 > 0:
print('<ul><li>{}</li>'.format(f))
else:
print('<li>{}</li>'.format(f))
print('</li></ul>')
Run Code Online (Sandbox Code Playgroud)
如果只有根目录,一级子目录和文件,它似乎运行良好.但是,添加另一级别的子目录会导致出现问题(因为我认为close标签在结束时输入的次数不够多).但是我很难理解它.
如果不能这样做,有没有更简单的方法呢?我正在使用Flask,但我对模板缺乏经验,所以也许我错过了一些东西.