【问题标题】:How to list folders and scan them [closed]如何列出文件夹并扫描它们[关闭]
【发布时间】:2020-06-29 12:55:36
【问题描述】:
我尝试用 python 做的事情在概念上很简单,
我需要扫描n个文件夹,思路是进入第一个文件夹,返回使用python进入下一个文件夹
【问题讨论】:
标签:
python
operating-system
【解决方案1】:
您可以为此使用os 模块。
它有 2 个功能可供您使用:
-
os.scandir:返回给定路径的 DirEntry 对象(可能是文件或文件夹)的迭代器。
-
os.walk:返回一个三元组的迭代器,形式为(dirpath,
目录名,文件名)
我通常更喜欢使用 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
希望对您有所帮助。有任何疑问都可以给我留言