How to find only the files in a directory in Python?

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))]

find only the files in a directory in Python


Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.