user3421420 user3421420 - 1 month ago 6
Python Question

Python && And Conditional Not Working

I'm looking to extract lines of a CSV file that meet BOTH conditions.

For example, I want to extract a line which features a certain unique code AND a specific date.

Currently, my code is only extracting lines which meet ONE of the conditions:

for line in log:

with open("log.csv", 'a') as csvfile:

if ("code123" and "29/07/2016") in line:

I've also tried

with open("log.csv", 'a') as csvfile:

if ("code123") and ("29/07/2016 ") in line:

But it seems extract lines that match that date but not also the unique code.

The format of the log file is a bit like this:

code123, 1001, 29/07/2016 14:01, 100

I've tried the code with and without a space after the date:

if ("code123") and ("29/07/2016") in line:


if ("code123") and ("29/07/2016 ") in line:

Incase the fact that there is a time in the same cell as the date is a problem.

But it just seems to extract lines that only match the date (and print any unique code that has a reading from the date, rather than the specified one).

Can anybody help?

The reason I am trying to do this is so I can separate a log file into separate files based on dates and unique ID's. So I want all the readings from a certain date for a certain key to be in one file.



if "code123" in line and "29/07/2016" in line:

Since and returns False or the last operand, ie.

x and y == y  # iff bool(x) is True and bool(y) is True

this part

("code123" and "29/07/2016") 

always evaluates to "29/07/2016" and you're left with

if "29/07/2016" in line:

The reason

a and b in c == (a and b) in c   

and not (a) and (b in c), is due to the operator precedence rules:

The precedence rules are also responsible for

a in c and b in c == (a in c) and (b in c)

since in has higher precedence than and. It might be better to add parenthesis for clarity in this case anyway though.