parser.add_argument('-e', dest='extname', nargs='+', action='store', metavar='EXT', default=[]) parser.add_argument('-s', dest='string', action='store', metavar='STRING') parser.set_defaults(recursive=True) args = parser.parse_args() exts = args.extname string = args.string rx = args.filename def check(f): if string: if string not in f.name: return False if rx: if not rx.match(f.name): return False if exts == []: return True else: return f.suffix in exts base.search(args.path, op=print, check=check, recursive=args.recursive)
def op(fname): # Do something when finding the file. if string: try: with open(fname) as fo: lines = fo.readlines() except: try: import codecs with codecs.open(fname, encoding='gb2312') as fo: lines = fo.readlines() except Exception as e: print('I just can not open %s\n' % fname, e) return if lines: flag = False for k, line in enumerate(lines, 1): if string in line: if not flag: print(fname, ' #line %d' % k) flag = True else: print('--- #line %d' % k) else: print(fname) base.search(path, op, check, args.recursive)
''' import os import pathlib import argparse import base parser = argparse.ArgumentParser( description='delete files with certain extension names in a path', parents=[base.searchFiles]) parser.add_argument('-e', dest='extname', nargs='+', action='store', metavar='EXT', default=[]) args = parser.parse_args() names = args.extname path = args.path def check(f): for name in names: if f.endswith('.' + name): return True return False base.search(path, os.remove, check, args.recursive)