A few suggestions:
- This doesn't need to be a one line function. Writing it on one line makes it much harder to understand and makes finding mistakes more difficult.
- Use
os.path.jointo assemble your full pathname + wildcard + extension. That way, you don't need to worry about whether or not your pathname is given with or without a trailing/ - If you're going to worry about a trailing
/in yourpathname, you should be equally worried about a preceding.in yourextension. glob.globalready returns a list with the matching files. I don't see any need for the complicated, nested list comprehensions you're using. Your function should essentially be a wrapper for callingglob.globthat simply makes combining the pathname + extension a little easier for the user.
That being said, here's how I might re-write this function:
import glob
import os
from typing import List
def find_files_with_extension(path_name: str, extension: str) -> List[str]:
extension_wildcard = "*"
if extension[0] != ".": //# suggestion #3
extension_wildcard += "."
extension_wildcard += extension
path_name_wildcard = os.path.join(path_name, "**", extension_wildcard) //# suggestion #2
return glob.glob(path_name_wildcard, recursive=True)