![](/img/trans.png)
[英]How to simply walk through directories and subdirectories and create archive if found certain files
[英]Can I loop through directories and subdirectories and store certain files in an array?
我有一个文件夹,其中包含许多子文件夹以及这些子文件夹中的图像。 我有循环遍历文件夹和子文件夹的代码,并一次打印出每个图像的名称。 我希望所有这些图像名称都存储在一个数组中。 如何让我的循环到 append 每个图像名称到同一个数组?
到目前为止,我只在 Linux 或 Matlab 上看到过类似的解决方案,但在 python 上没有。
files = []
#r=root, d=directories, f = files
for r, d, f in os.walk(path):
for face_image in f :
if face_image.endswith("g"): #to get all '.jpg' and all '.png' files
print(face_image)
当我运行上面的循环时,我打印了所有约 1000 个图像名称。 但是当我尝试在循环之外打印(face_image)时,只打印循环中最终图像的名称。 我现在这是因为我没有将每个名称附加到数组中,但不确定如何 go 关于这个? 任何帮助将不胜感激!
在您的打印语句之后,您可以使用files.append(face_image)
将面部图像添加到您的列表中。 循环完成后,所有有效的图像名称都将在列表中供您使用。
我不确定这是否是一个合法的问题。 您需要将 append 文件添加到列表中。
files = []
#r=root, d=directories, f = files
for r, d, f in os.walk(path):
for face_image in f :
if face_image.endswith("g"): #to get all '.jpg' and all '.png' files
print(face_image)
files.append(face_image)
你可以尝试这样的事情:
files = []
for r, d, f in os.walk(path):
# collect all images
files += [os.path.join(r, file) for file in f]
# filter images
files = [ff for ff in files if ff.endswith('g')]
或者更紧凑一点:
files = []
for r, d, f in os.walk(path):
# collect all images that end with 'g'
files += [os.path.join(r, file) for file in f if file.endswith('g')]
使用 pathlib 和递归 glob 模式:
from pathlib import Path
file_types = ("jpg", "png")
file_paths = []
for file_type in file_types:
file_paths.extend(Path(".").glob(f"**/*.{file_type}"))
file_names = [file_path.name for file_path in file_paths]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.