[Tutor] how to print lines which contain matching words or strings

Mats Wichmann mats at wichmann.us
Tue Nov 20 09:18:25 EST 2018


On 11/19/18 8:15 PM, Asad wrote:
> Hi Avi Gross /All,
> 
>              Thanks for the reply. Yes you are correct , I would like to to
> open a file and process a line at a time from the file and want to select
> just lines that meet my criteria and print them while ignoring the rest. i
> have created the following code :
> 
> 
>    import re
>    import os
> 
>    f3 = open(r'file1.txt',r)
>    f = f3.readlines()
>    d = []
>    for linenum in range(len(f)):
>         if re.search("ERR-1" ,f[linenum])
>            print f[linenum]
>            break
>         if re.search("\d\d\d\d\d\d",f[linenum])   --- > seach for a patch
> number length of six digits for example 123456
>            print f[line]
>            break
>         if re.search("Good Morning",f[linenum])
>            print f[line]
>            break
>         if re.search("Breakfast",f[linenum])
>            print f[line]
>            break
>         ...
>         further 5 more hetrogeneus if conditions I have
> 
> =======================================================================
> This is beginners approach to print the lines which match the if conditions
> .
> 
> How should I make it better may be create a dictionary of search items or a
> list and then iterate over the lines in a file to print the lines matching
> the condition.

We usually suggest using a context manager for file handling, so that
cleanup happens automatically when the context is complete:

with open('file1.txt', 'r') as f3:
    # do stuff
# when you get here, f3 is closed

There's no need to do a counting loop, using the count as an index into
an array. That's an idiom from other programing languages; in Python you
may as well just loop directly over the list (array)... lists are iterable.

for line in f:
   # search in line

Indeed, there's no real need to read all the lines in with readlines,
you can just loop directly over the file object - the f3 opened above:

for line in f3:
    # search in line

There's no need to use a regular expression search if your pattern is a
simple string, you can use the "in" keyword:

if "Breakfast" in line:
    print line

Keep your REs for more complex matches.

Do those help?



More information about the Tutor mailing list