Python how to implement something like .gitignore behavior

I need to list all the files in the current directory (.) (Including all subdirectories) and exclude some files, how.gitignore works ( http://git-scm.com/docs/gitignore )

With fnmatch ( https://docs.python.org/2/library/fnmatch.html ) I can "filter" files using a template

ignore_files = ['*.jpg', 'foo/', 'bar/hello*']
matches = []
for root, dirnames, filenames in os.walk('.'):
  for filename in fnmatch.filter(filenames, '*'):
      matches.append(os.path.join(root, filename))

how can I "filter" and get all files that do not match one or more elements of my "ignore_files"?

Thank you

+5
source share
2 answers

: fnmatch -style, fnmatch.filter .

, .

. ? filter :

for ignore in ignore_files:
    filenames = fnmatch.filter(filenames, ignore)

-, filter: , . :

, [n for n in names if fnmatch(n, pattern)], .

, , not:

for ignore in ignore_files:
    filenames = [n for n in filenames if not fnmatch(n, ignore)]

, , , join , . :

filenames = [os.path.join(root, filename) for filename in filenames]
for ignore in ignore_files:
    filenames = [n for n in filenames if not fnmatch(n, ignore)]
matches.extend(filenames)

.

, ( ), , , , , .

, , , , , :

filenames = (n for n in filenames 
             if not any(fnmatch(n, ignore) for ignore in ignore_files))

, , fnmatch.translate , , , fnmatch. , , *.jpg, , . , , , SO, - , , .

+7
matches.extend([fn for fn if not filename in ignore_files])

, - :

def reject(filename, filter):
    """ Takes a filename and a filter to reject files that match."""
    if len(filter)==0:
         return False
    else:
         return fnmatch.fnmach(filename, filter[0]) or reject(filename, filter[1:])

matches.extend([os.path.join(root, fn) for fn in filenames if not reject(fn, ignore_files)])

os.walk , - , , , ,

- :

filenames = set(filenames)  # convert to a set
for filter in ignore_files:
   filenames = filenames - set(fnmatch.filter(filenames, filter)) # remove the matches
matches.extend([os.path.join(root, fn) for fn in filenames])  # Add to matches
-1

All Articles