如何列出文件夹并扫描它们

用户13354476

我尝试用 python 做的事情在概念上很简单,

我需要扫描n个文件夹,想法是进入第一个文件夹,使用python返回并进入下一个文件夹

丹尼尔·冈萨雷斯·费尔南德斯

您可以os为此使用该模块。它有 2 个你可以使用的功能:

  1. os.scandir:返回给定路径的 DirEntry 对象(可以是文件或文件夹)的迭代器。

  2. os.walk : 以 (dirpath, dirnames, filenames) 形式返回一个三元组的迭代器

我通常更喜欢使用os.walk,但在你的情况下,os.scandir似乎合适你会做这样的事情:

from os import scandir

ROOT_DIRECTORY = "PATH TO DIRECTORY WHERE ALL THE FOLDERS YOU MENTION LIVE"

folders = scandir(ROOT_DIRECTORY)
for item in folders:
     # security check, in case there're also files in ROOT_DIRECTORY
     if item.is_dir():

         files_in_folder:scandir(item):
         for child in files_in_folder:

              # You say there will only be one file, but add security check too
              if child.is_file:
                  CALL_YOU_SPECIAL_FUNCTION(child)
                  break    # Optional: in case you just want to do this on first file

希望能帮助到你。任何疑问都给我留言

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章