Assume the directory where the files are located as shown below.
c:\pics\
a.png
b.jpg
subfolder\
c.png
d.jpg
I made a function like this. "Exts" is a file extension, but I think it will work even if you specify conditions other than the extension.
from pathlib import Path
def file_search(file_path, exts, search_subfolder):
"""
# file_path:Directory to search
# exts:File extension(Example:['*.jpg', '*.png']
"""
files = []
p = Path(file_path)
for ext in exts:
if search_subfolder:
files.extend(list(p.glob('**\\'+ext)))
else:
files.extend(list(p.glob(ext)))
return files
I will call it from main like this.
def main():
file_path = r'C:\pics' + '\\'
exts = ['*.jpg', '*.png']
files = file_search(file_path, exts, True)
pprint(files)
py searchpic.py
[WindowsPath('C:/pics/b.jpg'),
WindowsPath('C:/pics/subfolder/d.jpg'),
WindowsPath('C:/pics/a.png'),
WindowsPath('C:/pics/subfolder/c.png')]
That's why I was able to search for files with multiple extensions under the subfolder. In this case, the contents of the returned files are WindowsPath, not a string. For files, if strings are more convenient
files_str = list(map(lambda x: str(x), files))
You can make a list of character strings by converting it like this.
Recommended Posts