Saturday, June 16, 2012

Python File Parser

Here is a file parser that takes a file path as input from a user and then takes search terms from the user and returns results containing those search terms. I wrote this last month and decided to share it with the online community.

*If you use my code please give me credit! Enjoy! : )


#File Parser
#Written by G#42
#May 2012

import os
import time

#Open file for reading function
def fileChecker():
    File = str(None)
    while not os.path.isfile(File):
        print "[*] Your current file directory is %s: "% os.getcwd()

            File = raw_input("\n[*] What is the absolute path and file name of your log file? \n")
            fileOpen = open(File, "r")
            fileLines = fileOpen.readlines()
            print "\n[*] ERROR! Please provide an absolute path to your file!!!!!\n"

        if os.path.isfile(File) == True:
            print "\n[*] You entered %s as your file.\n" %File
    return fileLines         

#Defining search terms function
def searchFor():  
    terms = []
    while not False:

        searchTerm = raw_input("\n[*] Please enter a search term:\n\n")
        print "\n\n[*] Your search terms: %s \n" %terms
        Done = ""
        while Done != "yes" and Done != "no":
            Done = raw_input("\n\n[*] Would you like to enter another search term? yes or no:\n\n")

            if Done != "yes" and Done != "no":
                print "\n\n[*] You responded with %s. Please respond with yes or no!\n\n"% Done
        if Done == "no":
            return terms

#Perform search function
def searchGo():
    lines = fileChecker()
    searchTerms = searchFor()
    results = []
    output = ""
    print "\n[*] Searching file for %s...\n\n"% searchTerms
    print "\n\n[*][*] Here are your search results containing your search terms of %s [*][*]\n\n"% searchTerms
    for line in lines:
        for terms in searchTerms:
            if terms in line:
    for result in results:
        output = output + "[*] " + result + "\n"

    print output

#Called functions


No comments:

Post a Comment