1

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:   
            print(line)

I've also tried

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

    if ("code123") and ("29/07/2016 ") in line:   
            print(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:   

and

    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.

user3421420
  • 103
  • 9
  • 1
    Possible duplicate of [How do I test one variable against multiple values?](http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) – Łukasz Rogalski Sep 05 '16 at 16:27
  • Why not just `if ("code123" in line) and (29/07/2016 in line):` ? – galah92 Sep 05 '16 at 16:28
  • in all of the cases you used, python is checking `if ("code123") == True` rather than `if ("code123") in line`. Use `if ("code123" in line) and ("29/07/2016" in line): ` – James Sep 05 '16 at 16:28
  • While it's not 100% percent duplicate, it's essentially the same, it's only requires substitution from *equals* to *is in*, and from *or* to *and* – Łukasz Rogalski Sep 05 '16 at 16:29

1 Answers1

0

try

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: http://www.tutorialspoint.com/python/operators_precedence_example.htm

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.

thebjorn
  • 26,297
  • 11
  • 96
  • 138