简体   繁体   中英

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 search multiple .txt files in a defined directory for the string and then either print the result, or open the .txt file using the default text editor.

Can someone please point me in the right direction for this search feature?

Thanks in advance!

Edit: This is what I have so far. I cant use grep as this program wil be running on Windows as well as OSX. I have yet to test on Windows, but on OSX my results are access denied.

import os
    import subprocess

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

    thedir = './f'
    for file in os.listdir(thedir):
        document = os.path.join(thedir, file)
        for line in open(document):
            if text in line:
                subpocess.call(document, shell=True)

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 in os.walk(start):
        for f in files:
            path = os.path.join(root, f)
            for line_number, line in finder(path):
                yield path, line_number, line.strip()

if __name__ == "__main__":
    import sys
    if not len(sys.argv) == 3:
        print("usage: word directory")
        sys.exit(1)
    word = sys.argv[1]
    start = sys.argv[2]
    for path, 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)'

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...

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 in open(filepath):
        if text in line:
            subprocess.call(filepath, shell=True)
            break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM