Active Members MrGrj Posted December 22, 2016 Active Members Report Posted December 22, 2016 (edited) Un mic programel pentru a cauta in toate sub-directoarele dintr-un director dat o anumita fraza/cuvant: from os import walk from os.path import join import argparse def get_files(base_path, extension=None): for dirpath, _, filenames in walk(base_path): for filename in filenames: if filename.endswith(extension): yield join(dirpath, filename) def search_sentence_in_files(files, sentence): for filepath in files: with open(filepath) as fp: for line_number, line in enumerate(fp): if sentence in line: yield filepath, line_number, line.strip() def main(files, sentence): results = search_sentence_in_files(files, sentence) for filepath, line, content in results: print('[# FILE PATH #] {} ...'.format(filepath)) print('[# LINE NUMBER #] At line {}'.format(line)) print('[# LINE CONTENT #] Content: {}'.format(content)) print('-' * 80) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Search text in files') parser.add_argument('sentence') parser.add_argument('-p', '--basepath', help='folder in wich files will be examinated', default=r'default_path') parser.add_argument('-e', '--extension', help='extension of files to examine', default='.txt') args = parser.parse_args() files = get_files(args.basepath, args.extension) main(files, args.sentence) Poate fi rulat cu Python 2.x/3.x. Poate primi ca argumente: - cuvantul / fraza dorita - basepath (in ce director sa caute) - extensia fisierelor in care doriti sa cautati fraza / cuvantul dorit. De adaugat: - indexare - regex functionality Enjoy Edited December 22, 2016 by MrGrj 3 Quote