[PYTHON] How to list files under the specified directory in a list (multiple conditions / subdirectory search)

Assume the directory where the files are located as shown below.

c:\pics\
	a.png
	b.jpg
	subfolder\
		c.png
		d.jpg

code

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)

Execution result

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

How to list files under the specified directory in a list (multiple conditions / subdirectory search)
How to get a list of files in the same directory with python
How to delete multiple specified positions (indexes) in a Python list
How to use the grep command to recursively search directories and files to a specified depth
How to get the last (last) value in a list in Python
How to display a specified column of files in Linux (awk)
How to clear tuples in a list (Python)
Delete all pyc files under the specified directory
How to get the files in the [Python] folder
Recursively search the specified directory to see the file
How to read a file in a different directory
How to read all the classes contained in * .py in the directory specified by Python
I want to see a list of WebDAV files in the Requests module
How to know the current directory in Python in Blender
How to reference static files in a Django project
[Python] How to output the list values in order
How to identify the element with the smallest number of characters in a Python list?
How to check in Python if one of the elements of a list is in another list
How to find the first element that matches your criteria in a Python list
How to slice a block multiple array from a multiple array in Python
[Linux] Grep multiple gzip files in a directory at once
How to define multiple variables in a python for statement
How to generate a query using the IN operator in Django
How to get a list of built-in exceptions in python
How to connect the contents of a list into a string
Get the value of a specific key up to the specified index in the dictionary list in Python
How to pass the execution result of a shell command in a list in Python (non-blocking version)
How to handle multiple versions of CUDA in the same environment
[sh] How to store the command execution result in a variable
How to determine the existence of a selenium element in Python
How to compare lists and retrieve common elements in a list
How to get all the possible values in a regular expression
Search the file name including the specified word and extension in the directory
How to check the memory size of a variable in Python
[Introduction to Python] How to use the in operator in a for statement?
How to check the memory size of a dictionary in Python
How to get the vertex coordinates of a feature in ArcPy
[Ln] How to paste a symbolic link in a directory is complicated
For Windows: Get a list of directories and files under a specific directory.
List all files under the current directory line by line with full path
How to specify a .ui file in the dialog / widget GUI in PySide
[Python] How to put any number of standard inputs in a list
[Introduction to Python] How to sort the contents of a list efficiently with list sort
[Linux] Command to get a list of commands executed in the past
I want to sort a list in the order of other lists
[Introduction to Python] How to delete rows that meet multiple conditions in Pandas.DataFrame
How to write a string when there are multiple lines in python
How to format a list of dictionaries (or instances) well in Python
How to sort by specifying a column in the Python Numpy array.
[Python] How to convert a 2D list to a 1D list
Change the list in a for statement
[linux] Split files to the specified size
How to get a stacktrace in python
How to read CSV files in Pandas
I wanted to know the number of lines in multiple files, so I tried to get it with a command
[Unzip] How to decompress only arbitrary files from those whose directory delimiter in the zip file is backslash
How to achieve something like a list of void * (or variant) in Go?
How to count the number of elements in Django and output to a template
A memorandum of how to execute the! Sudo magic command in Jupyter Notebook
Search for files with line feed code CR + LF under the current directory
How to make a Raspberry Pi that speaks the tweets of the specified user