简体   繁体   English

如何遍历目录以查找文件夹

[英]How to iterate through directory to find folders

I am trying to iterate through directory to find folders to change the path.我正在尝试遍历目录以查找文件夹以更改路径。 At the moment I am using:目前我正在使用:

root = tk.Tk(); root.withdraw()  # close the tkinter root window
path = filedialog.askdirectory()  # open file dialogue box

to select the folder.到 select 文件夹。 After being selected a loop is run through that folder and scans all the images within it.被选中后,将在该文件夹中运行一个循环并扫描其中的所有图像。 However I have a lot of folders to scan through and was wondering if there was a way to scan through a directory and just find the folders so that they could be scanned automatically in python. So that for each folder it changed the path and this looped over all the folders.但是我有很多文件夹要扫描,想知道是否有一种方法可以扫描目录并找到文件夹,以便可以在 python 中自动扫描它们。这样对于每个文件夹,它都会更改路径并循环在所有文件夹上。 Any help would be much appreciated.任何帮助将非常感激。

It sounds like you are looking for os.walk .听起来您正在寻找os.walk

os.walk(top, topdown=True, onerror=None, followlinks=False)¶ os.walk(top, topdown=True, onerror=None, followlinks=False)¶

Generate the file names in a directory tree by walking the tree either top-down or bottom-up.通过自上而下或自下而上遍历目录树来生成目录树中的文件名。 For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).对于树中以目录 top 为根的每个目录(包括 top 本身),它产生一个三元组(dirpath、dirnames、filenames)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM