# written for python 3 import os def check_balance(characters): '''Return -1 if all delimiters are balanced or return the char number of the first mismatched delimiter. ''' openers = {'(': ')', '{': '}', '[': ']', '“': '”', '‹': '›', '«': '»', '【': '】', '〈': '〉', '《': '》', '「': '」', '『': '』'} closers = set(openers.values()) stack = [] for i, c in enumerate(characters, start=1): if c in openers: stack.append(openers[c]) elif c in closers: if not stack or c != stack.pop(): return i return -1 def scan(directory, encoding='utf-8'): for dirpath, dirnames, filenames in os.walk(directory): for filename in filenames: fullname = os.path.join(dirpath, filename) with open(fullname, 'r', encoding=encoding) as f: try: characters = f.read() except UnicodeDecodeError: continue position = check_balance(characters) if position >= 0: print('{0!r}: {1}'.format(position, fullname)) scan('.')