Python && And Conditional Not Working
<p>I'm looking to extract lines of a CSV file that meet BOTH conditions.</p>

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

<p>Currently, my code is only extracting lines which meet ONE of the conditions:</p>

<p>for line in log:</p>

<pre><code>with open("log.csv", 'a') as csvfile:

    if ("code123" and "29/07/2016") in line:   
            print(line)
</code></pre>

<p>I've also tried</p>

<pre><code>with open("log.csv", 'a') as csvfile:

    if ("code123") and ("29/07/2016 ") in line:   
            print(line)
</code></pre>

<p>But it seems extract lines that match that date but not also the unique code.</p>

<p>The format of the log file is a bit like this:</p>

<p>code123, 1001, 29/07/2016 14:01, 100</p>

<p>I've tried the code with and without a space after the date:</p>

<pre><code>    if ("code123") and ("29/07/2016") in line:   
</code></pre>

<p>and</p>

<pre><code>    if ("code123") and ("29/07/2016 ") in line: 
</code></pre>

<p>Incase the fact that there is a time in the same cell as the date is a problem.</p>

<p>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).</p>

<p>Can anybody help?  </p>

<p>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.</p>

<p>try</p>

<pre><code>if "code123" in line and "29/07/2016" in line:
</code></pre>

<p>Since <code>and</code> returns <code>False</code> or the last operand, ie.</p>

<pre><code>x and y == y  # iff bool(x) is True and bool(y) is True
</code></pre>

<p>this part</p>

<pre><code>("code123" and "29/07/2016") 
</code></pre>

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

<pre><code>if "29/07/2016" in line:
</code></pre>

<p>The reason </p>

<pre><code>a and b in c == (a and b) in c   
</code></pre>

<p>and not <code>(a) and (b in c)</code>, is due to the operator precedence rules: <a href="http://www.tutorialspoint.com/python/operators_precedence_example.htm" rel="nofollow">http://www.tutorialspoint.com/python/operators_precedence_example.htm</a></p>

<p>The precedence rules are also responsible for</p>

<pre><code>a in c and b in c == (a in c) and (b in c)
</code></pre>

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

python conditional extraction conditional-operator data-extraction