Home > other >  Printing full path to all possible png files in directory
Printing full path to all possible png files in directory

Time:04-29

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?

CodePudding user response:

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.

CodePudding user response:

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)

  • Related