Python list dir仅用于列表目录
我需要列出目录并检测其中的文件夹和文件 为此,我想制作两个变量,一个名为Python list dir仅用于列表目录,python,flask,jinja2,Python,Flask,Jinja2,我需要列出目录并检测其中的文件夹和文件 为此,我想制作两个变量,一个名为content\u folders,它将返回文件夹,另一个用于文件,但我在制作content\u folders时遇到了问题 def folder_check(root_path): for item in root_path: if os.path.isdir(item): return item 这就是我试图列出内容\u文件夹的方法,然后使用它: elif c
content\u folders
,它将返回文件夹,另一个用于文件,但我在制作content\u folders
时遇到了问题
def folder_check(root_path):
for item in root_path:
if os.path.isdir(item):
return item
这就是我试图列出内容\u文件夹的方法
,然后使用它:
elif content == "brandings":
title="Brandings"
root_path = os.listdir(os.path.join(
app.static_folder,
f'content/{content}/'))
content_folders = folder_check(root_path)
return render_template('base.html',
content=content,
title=title,
content_folders=content_folders
)
它在我的jinja模板中不返回任何值,因此我无法创建for循环。可能就是您想要的
通过遍历目录树生成目录树中的文件名
自上而下或自下而上。对于树中根在的每个目录
目录top(包括top本身),它生成一个3元组(dirpath,
目录名、文件名)
例如:
import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
print(root, "consumes", end=" ")
print(sum(getsize(join(root, name)) for name in files), end=" ")
print("bytes in", len(files), "non-directory files")
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
假设您在共享的第一个代码段中达到了
if
条件。否则,您将不返回任何值。您的代码似乎没有预料到这种情况。是的,它不返回任何内容,我也不知道如何使其工作。listdir只返回名称,但您需要条件中的完整路径。即使这样,folder\u check
也只会返回找到的第一个文件夹,而不是所有文件夹。我想我只需要使用两个文件夹来分割图像和文件夹,这会简单得多。不,他们不会尝试进行递归遍历。(我认为您可以放置一个无条件的中断
,以便它在第一次迭代后退出,然后只输出顶级目录的内容,但我认为代码仍然可能会令人困惑。它至少需要代码中的一些澄清注释来帮助读者。)