How to list directory files excluding files in gitignore?

Viewed 87

I am trying to list all directory files, but without files (or patterns) from .gitignore.

For example, script runs inside main directory:

# .gitignore
dir2/
py.cache

# directory structure
.
├── .gitignore
├── subdir
│   ├── dir1
│   │   ├── file1
│   │   └── py.cache
│   └── dir2
│       ├── file2
│       └── py.cache
└── pydir
    ├── script.py
    └── py.cache

And expected result is:

[Path("subdir/dir1/file1"), Path("pydir/script.py")]

I am looking for something like:

Path(".").iterdir(include_gitignore=True)

# or

for p in Path(".").iterdir():
    if p not in gitignore:
        # ...
1 Answers

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