如何在python中逐子文件夹迭代一个文件夹



我有一个文件夹,里面有成千上万个。ai文件。这个文件夹的排列方式是,它最初有以客户名字命名的子文件夹,在每个子文件夹中都有一个独特的目录,其中包含一些或许多子文件夹,或者子文件夹中的子文件夹……包含。ai文件,或者没有子文件夹,只有。ai文件。

我需要一个程序,将迭代通过客户子文件夹内的每个。ai文件名(不管有多少子文件夹,或子文件夹内的子,等等…),并将其追加到一个列表。然后,我将这个列表,并对它做一些ocr的东西,但一旦完成,我将清除列表,并转移到下一个子文件夹。

这是我用来尝试的代码,但它失败了。它有时返回一个空列表,或者一个只有一个文件名的列表,而每次它应该返回一个包含一个或多个.ai文件名的列表。

def folder_loop(folder):
temp_list = []
for root, dirs, files in os.walk(folder):
for dir in dirs:
for file in dir:
if file.endswith("ai"):
temp_list.append(os.path.join(root, file))
print(temp_list)
temp_list.clear()

我是一个初学者,我几乎不明白代码在做什么,所以我不惊讶它不能工作。什么好主意吗?

您可以尝试以下操作:

如果您想给函数基本文件夹,其中包含所有客户文件夹,然后想为每个客户文件夹列出所有.ai-文件(来自每个子级别):

from pathlib import Path
def folder_loop(folder):
for path in Path(folder).iterdir():
if path.is_dir():
yield list(path.rglob("*.ai"))

Path.rglob("*.ai")递归地将给定的Path及其所有子文件夹归为.ai-files。

使用它:

the_folder = "..."
for file_list in folder_loop(the_folder):
print(file_list)
# do whatever you want to do with the files

如果你想给它一个文件夹,并且想要一个包含所有.ai文件的列表:

def folder_loop(folder):
return list(Path(folder).rglob("*.ai"))

这里产生/返回的列表包含Path-对象(非常方便)。如果你想要字符串,那么你可以用

....
yield list(map(str, path.rglob("*.ai")))

等。

这里有一个社区帖子,里面有一些愚蠢的完整答案。

话虽如此,我在我的个人工具工具箱中有下面的方法。

def get_files_from_path(path: str=".", ext=None) -> list:
"""Find files in path and return them as a list.
Gets all files in folders and subfolders
See the answer on the link below for a ridiculously
complete answer for this.
https://stackoverflow.com/a/41447012/9267296
Args:
path (str, optional): Which path to start on.
Defaults to '.'.
ext (str/list, optional): Optional file extention.
Defaults to None.
Returns:
list: list of full file paths
"""
result = []
for subdir, dirs, files in os.walk(path):
for fname in files:
filepath = f"{subdir}{os.sep}{fname}"
if ext == None:
result.append(filepath)
elif type(ext) == str and fname.lower().endswith(ext.lower()):
result.append(filepath)
elif type(ext) == list:
for item in ext:
if fname.lower().endswith(item.lower()):
result.append(filepath)
return result

最新更新