Skip to content

Instantly share code, notes, and snippets.

@chrK
Created July 28, 2012 18:56
Show Gist options
  • Save chrK/3194414 to your computer and use it in GitHub Desktop.
Save chrK/3194414 to your computer and use it in GitHub Desktop.
Python: Treewalker
# -*- coding: utf-8 -*-
import os
import fnmatch
import re
root = os.getcwd()
includes = ['includes', ] # For files only.
excludes = ['excludes', ] # For dirs and files.
# Transform glob patterns to regular expressions:
includes = r'|'.join([fnmatch.translate(x) for x in includes])
excludes = r'|'.join([fnmatch.translate(x) for x in excludes]) or r'$.'
for root, dirs, files in os.walk(project_root):
# Exclude dirs:
dirs[:] = [os.path.join(root, d) for d in dirs]
dirs[:] = [d for d in dirs if not re.match(excludes, d)]
# Exclude/include files:
files = [os.path.join(root, f) for f in files]
files = [f for f in files if not re.match(excludes, f)]
files = [f for f in files if re.match(includes, f)]
for fname in files:
(dir_name, file_name) = os.path.split(fname)
(file_base_name, file_extension) = os.path.splitext(file_name)
print dir_name, file_name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment