I recently came across a requirement to find all the files (only the files not any sub-folders) in a folder and add them to a list variable. Here is a simple technique to file only the files in a directory. Here, I have used pathlib and os.listdir to check if it is a file and get the list of files.
from os import listdir from pathlib import PurePath, Path folderPath = Path("samples") listOfFiles = [file for file in listdir(folderPath) if Path.is_file(PurePath.joinpath(folderPath, file))] print(listOfFiles)
- About os.listdir at Python Docs.