Searching for a list of strings in a file with Python

Peter Otten __peter__ at web.de
Mon Oct 14 02:33:41 EDT 2013


Starriol wrote:

> Hi guys,
> 
> I'm trying to search for several strings, which I have in a .txt file line
> by line, on another file. So the idea is, take input.txt and search for
> each line in that file in another file, let's call it rules.txt.
> 
> So far, I've been able to do this, to search for individual strings:
> 
> [code]import re
> 
> shakes = open("output.csv", "r")
> 
> for line in shakes:
>     if re.match("STRING", line):
>         print line,[/code]
> 
> How can I change this to input the strings to be searched from another
> file?

Assuming every line in input.txt contains a regular expression and you don't 
care which one matches:

shakes = open("output.csv")

# you will iterate over the regex multiple times, 
# so put them in a list
rattles = [line.strip() for line in open("input.txt")]

for line in shakes:
    for expr in rattles:
        if re.match(expr, line):
            print line,
            break # out of the for-rattles loop
                  # at the first matching regex




More information about the Python-list mailing list