hsifyllej hsifyllej - 13 days ago 12
Python Question

How to check if an item in a list appears in csv?

I have a list of items:

List = ['apple', 'banana', 'orange']


and a csv file:

apple
kiwi
banana
orange
pear


I am trying to see for each item in the list if it matches the first column of the csv, and if it does, append a '1' to the end of the row (otherwise appending a '0'), but I am a bit lost. The code below is pretty much what I'm trying to get the end result to be.

apple, 1
kiwi, 0
banana, 1
orange, 1
pear, 0


I am very new to python and would really appreciate any help! Thanks

Answer

I tried below code, which will store result in CSV

import csv

lists = ['apple', 'banana', 'orange']
nf = csv.writer(open("output.csv", "w"))
with open('input.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        if(''.join(row) in lists):
            nf.writerow([''.join(row),1])
        else:
            nf.writerow([''.join(row),0])

OUTPUT in CSV

apple,1
kiwi,0
banana,1
orange,1
pear,0