here2learn
here2learn

Reputation: 61

Multiple Search Terms and Output Files

I have a file I'm searching through and printing the results to a file. I'm wondering if it's possible to amend the code below to read in multiple search terms i.e. print any line that has "test" or "hello" (user will specify) in it but have Python create a new output file for each search term?

i.e. Ofile1 would hold all lines containing "test" Ofile2 would hold all lines containing "hello" and so on

f = open('file3.txt') #input file

term = raw_input("What would you like to search for?") #takes an input to be searched

for line in f:
    if term in line:
        print (line) #print line of matched term

f.close() #close file

Is this possible to do?

Upvotes: 0

Views: 44

Answers (2)

new
new

Reputation: 1

Split your term by spaces. then use a for loop to loop through all of the terms.

ex:

terms = term.split(" ")
for t in terms:
    filename = t +"_output.txt"
    o = open(filename,'w')
    for line in f:
        if t in line:
            o.write(line) #print line of matched term
    o.close() 

Upvotes: 0

Juan Antonio
Juan Antonio

Reputation: 2614

Based of @new user code (improved some error) you could do something like this:

terms = raw_input("What would you like to search for?")
terms = terms.split(" ")
for term in terms:
    f = open('text.txt')
    filename = '{}_output.txt'.format(term)
    o = open(filename, 'w')
    for line in f:
        if term in line:
            o.write(line)
    o.close()
    f.close()

Maybe you can think that is better open the file once and check some term per each line. Depending of number of terms it will be more or less efficient, if you want could research about it using really big files to check execution times and learn a bit more.

Upvotes: 1

Related Questions