Jump to content
MrGrj

[Python] Cautare fisiere in director cu o anumita extensie - part 1

Recommended Posts

  • Active Members
Posted (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 by MrGrj
  • Upvote 3

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...