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.
os.path.join to 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 your
pathname, you should be equally worried about a preceding
. in your
glob.glob already 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 calling
glob.glob that simply makes combining the pathname + extension a little easier for the user.
That being said, here's how I might re-write this function:
from typing import List
def find_files_with_extension(path_name: str, extension: str) -> List[str]:
extension_wildcard = "*"
if extension != ".": # 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)