'Printing full path to all possible png files in directory
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?
Solution 1:[1]
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.
Solution 2:[2]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Rabinzel |
