search.py 搜索文件或文件中的word
''' Created on Jan 28, 2013 @author: changxue @summary: to look for a file by filename within specified directory, or look for some word in files ''' import os import sys def search_file(key, scope): for parent, dirs, files in os.walk(scope): if key in files: print parent, key def search_content(key, scope): for parent, dirs, files in os.walk(scope): for f in files: file_path = os.path.join(parent, f) count = 0 with open(file_path, 'r') as fp: content = fp.readlines() for line in content: count += 1 if line.find(key) != -1: print "%s line number: %d" % (file_path, count) if __name__ == '__main__': usage = """Usage: \t search -f|-c|-all key scope \t -f: search file in scope \t -c: search content in files of scope """ if len(sys.argv) < 4: print usage sys.exit() key = sys.argv[2] scope = sys.argv[3] if sys.argv[1] == '-f': search_file(key, scope) elif sys.argv[1] == '-c': search_content(key, scope) elif sys.argv[1] == '-all': search_file(key, scope) search_content(key, scope) else: print usage