1
votes

I have the following csv file:

Value1,Value2,Value3,Value4
11,12,27,28
5,6,101,102
111,112,55,56
1,7,33,34
3,4,55,57

I want to print lines if Value1 & Value2 are consecutive AND Value3 & Value4 are consecutive. The desired answer would be:

11,12,27,28
5,6,101,102
111,112,55,56

I tried something like this but it didn't work

f = open('test.csv', 'rU')
for line in csv.reader(f):
    if line [1] == line [0] + 1 & line [4] == line [3] + 1:
        print line
f.close

Any help is appreciated. Thanks!

3
Change & to and, the first is bitwise AND which you don't want, you want logical AND.Cory Kramer

3 Answers

0
votes

The big problem, you have to change & to the word and. Read CoryKramers comment for more of an explanation as to why. A couple more things, it is always better to use with open when dealing with files. You want to skip the first line, since it is just a header line, so I added that. The values you read in from the CSV are strings, not integers, so trying to add to a string won't work, so you have to cast them as ints. Finally, the indicies you used were off, you did 1 0 4 3, when there is no 4 index in the list. It should have been 1 0 3 2. This outputs what you want:

import csv
with open('test.csv', 'rU') as f:
    csvfile = csv.reader(f, delimiter=',')
    for line in csvfile:
        if 'Value1' not in line:
            if int(line[1]) == int(line[0]) + 1 and int(line[3]) == int(line[2]) + 1:
                print ','.join(line)
0
votes

You should change your code to

with open('test.csv', 'r') as f:
    next(f) # Skip first line with headers
    for line in csv.reader(f):
        if line [1] == line [0] + 1 and line [4] == line [3] + 1:
            print line

see the and in the if because & is a bitwise AND operator

0
votes

You have a few problems.

  1. You're using & instead of and. (Look up bitwise & versus and)
  2. You have a typo in your code: line[4] and line[3] should be line[3] and line[2] respectively.
  3. You should be surrounding your line[#] with int() to cast it explicitly. So int(line[#]).
  4. You need to advance your file so it doesn't hit the first line.

Finally, as a matter of style, you should not have extra spaces around [#] and you should use with open.

Here's some fixed code:

import csv
with open('test.csv', 'r') as f:
    next(f)
    for line in csv.reader(f):
        if int(line[1] == int(line[0]) + 1 and int(line[3]) == int(line[2]) + 1:
            print(line)