Skip to content Skip to sidebar Skip to footer

Python Searching For String And Printing The File It Is In

I am working on a small program for work, and I have looked everywhere for help on this! What I'm trying to do is to allow the user to put in string to search. The program will sea

Solution 1:

There are much better tools to do this (grep was mentioned, and it is probably the best way to go).

Now, if you want a Python solution (which would run very slow), you can start from here:

import os

def find(word):
    def _find(path):
        with open(path, "rb") as fp:
            for n, line in enumerate(fp):
                if word in line:
                    yield n+1, line
    return _find

def search(word, start):
    finder = find(word)
    for root, dirs, files inos.walk(start):
        for f in files:
            path = os.path.join(root, f)
            for line_number, line in finder(path):
                yieldpath, line_number, line.strip()

if __name__ == "__main__":
    import sys
    ifnotlen(sys.argv) == 3:
        print("usage: word directory")
        sys.exit(1)
    word = sys.argv[1]
    start = sys.argv[2]
    forpath, line_number, line in search(word, start):
        print ("{0} matches in line {1}: '{2}'".format(path, line_number, line))

Please take this with a grain of salt: it will not use regular expressions, or be smart at all. For example, if you try to search for "hola" it will match "nicholas", but not "Hola" (in the latter case, you could add a line.lower() method.

Again, it is just a beginning to show you a possible way to start. However, please PLEASE use grep.

Cheers.

Sample run (I called this script "pygrep.py"; $ is the command prompt):

$python pygrep.py finder .                           
./pygrep.py matches in line 12: 'finder = find(word)'
./pygrep.py matches in line 16: 'for line_number, line in finder(path):'
./pygrep.py~ matches in line 11: 'finder = find(word)'

Solution 2:

below are hints to your answer :)

You can use os.walk to traverse all the files in the specified directory structure, search the string in the file, use subprocess module to open the file in the required editor...

Solution 3:

import os
import subprocess

text = str(raw_input("Enter the text you want to search for: "))

thedir = 'C:\\your\\path\\here\\'for file in os.listdir(thedir):
    filepath = thedir + file
    for line inopen(filepath):
        if text in line:
            subprocess.call(filepath, shell=True)
            break

Post a Comment for "Python Searching For String And Printing The File It Is In"