在目录中打印到所有可能的PNG文件的完整路径

发布于 2025-01-25 09:25:37 字数 265 浏览 1 评论 0原文

我需要在目录“图像”中显示所有PNG文件。问题在于有一个子目录的“附加文件”,其中还有一个png。

import glob
my_path = "images"
possible_files = os.path.join(my_path, "*.png")
for file in glob.glob(possible_files):
    print(file)

我如何在此目录中显示所有PNG文件的完整路径,包括没有新循环的子目录中的PNG文件?

I need to display all png files in directory 'images'. The problem is there is subdirectory 'additional files' with one more png in it.

import glob
my_path = "images"
possible_files = os.path.join(my_path, "*.png")
for file in glob.glob(possible_files):
    print(file)

How can i display full path to all png files in this directory including png files in subdirectories without new loop?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

初懵 2025-02-01 09:25:37

您可以使用OS.Walk方法。

import glob
import os

for (dirpath, dirnames, filenames) in os.walk(YOURPATH):
    possible_files = os.path.join(dirpath, "*.png")
    for file in glob.glob(possible_files):
        print(file)

“文件名”为您提供了文件的名称,您可以使用'dirpath'和“ dirnames”来确定它们来自哪个目录,因此您甚至可以包含一些子目录并跳过其他目录。

You can use os.walk method.

import glob
import os

for (dirpath, dirnames, filenames) in os.walk(YOURPATH):
    possible_files = os.path.join(dirpath, "*.png")
    for file in glob.glob(possible_files):
        print(file)

'filenames' gives you the name of the files and you can use 'dirpath' to and 'dirnames' to determine which directory they are from, so you can even include some sub directories and skip others.

執念 2025-02-01 09:25:37

怎么样?您已经在使用OS库。

my_path = "images"
out = [os.path.abspath(x) for x in glob.glob(my_path+"\\**\\*.png", recursive=True)]

out是一个列表,其中列出了所有png带有FullPath的文件(带有子目录)

How about this? You are already using the os library.

my_path = "images"
out = [os.path.abspath(x) for x in glob.glob(my_path+"\\**\\*.png", recursive=True)]

out is a list with all png files with fullpath (with subdirectories)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文