Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pathlib

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:
        # ...
like image 729
Max Smirnov Avatar asked Sep 14 '25 21:09

Max Smirnov


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))
like image 102
KetZoomer Avatar answered Sep 17 '25 11:09

KetZoomer