How to list directory files excluding files in gitignore? [duplicate]

Some code like this should work:

from fnmatch import fnmatch

files = Path("directoryToList").iterdir()
with open(".gitignore") as gitignore_file:
    gitignore = [line for line in gitignore_file.read().splitlines() if line]

filenames = (file for file in files 
             if not any(fnmatch(file, ignore) for ignore in gitignore))