psilos
psilos

Reputation: 21

How to print lines from a file with multiple conditions in Python?

I got a short question regarding python: How to do read specific lines from a file? By using multiple filters, bellow is my current code that doesn't show the expected results for me:

for line in loglist:
    if (str('send') and str('packet')) in line:
        print line

So, what I want is to print lines that contains both the words "send" and "packet", but it prints all lines that contain either send or packet.

many thanks in advance guys,

Upvotes: 2

Views: 1852

Answers (4)

engineerC
engineerC

Reputation: 2868

(str('send') and str('packet'))

Evaluates to "packet" with is always true (not what you want). Try

if "send" in line and "packet" in line

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213271

You should separate your conditions: -

if ('send' in line) and ('packet' in line):
    print line

If you do: -

if (str('send') and str('packet')) in line:

It is similar to saying: -

if 'packet' in line:

Because, the inner condition is and which returns the last false value, or if all are True, then returns the last value.

So, str('send') and str('packet') is equivalent to 'packet'

And you don't need that str wrapping around them.

Upvotes: 3

BrtH
BrtH

Reputation: 2664

(str('send') and str('packet')) evaluates to True. So you are saying True in line, which doesn't work of course. What you need is

if 'send' in line and 'packet' in line):
    print line

BTW, it makes no sense to run str() on a string, why would you convert a string to a string?

Upvotes: -1

mgilson
mgilson

Reputation: 309939

One way:

if all( x in line for x in ('send','packet')):

This is the most efficient way to do it if you need to scale up to an arbitrary number of conditions ...

Another way:

if ('send' in line) and ('packet' in line):

With just 2 checks, this is likely to be faster than the above.

Upvotes: 3

Related Questions