Home > Mobile >  Comparing Data Inside CSV Files
Comparing Data Inside CSV Files

Time:12-05

I am brand new to Python, so go easy on me!

I am simply trying to compare the values in two lists and get an output for them in yes or no form.

Image of the CSV file storing values in:

My code looks like this:

import csv

f = open("datatest.csv")
reader = csv.reader(f)

dataListed = [row for row in reader]

rc = csv.writer(f)  

column1 = []
for row in dataListed:
    column1.append(row[0])
    
column2 = []
for row in dataListed:
    column2.append(row[1])

for row in dataListed:
    if (column1) > (column2):
        print ("yes,")
    else:
        print("no,")

Currently, the output is just no, no, no, no, no ..., when it should not look like that based on the values!

I will show below what I have attempted, any help would be huge.

CodePudding user response:

for row in dataListed:
    if (column1) > (column2):
        print ("yes,")
    else:
        print("no,")

This loop is comparing the same column1 and column2 variables each time through the loop. Those variables never change.

The code does not magically know that column1 and column2 actually mean "the first column in the current row" and "the second column in the current row".

Presumably you meant something like this instead:

if row[0] > row[1]:

... because this actually does use the current value of row for each loop iteration.

CodePudding user response:

You can simplify your code and obtain the expected result with something like this:

import csv
from pathlib import Path

dataset = Path('dataset.csv')

with dataset.open() as f:
    reader = csv.reader(f)
    headers = next(reader)

    for col1, col2 in reader:
        print(col1, col2, 'yes' if int(col1) > int(col2) else 'no', sep=',')

For the sample CSV you posted in the image, the output would be the following:

1,5,no
7,12,no
11,6,yes
89,100,no
99,87,yes

CodePudding user response:

Here you can get a simple alternative for you program.

f=open("sample.csv")

for each in f:
    header=""
    row=each.split(",")[enter image description here][1]
    try:
        column1=int(row[0])
        column2=int(row[1])
        if column1>column2:
            print(f"{column1}\t{column2}\tYes")
        else:
            print(f"{column1}\t{column2}\tNo")
    except:
        header=each.split(",")
        head=f"{header[0]}\t{header[1].strip()}\tresult"
        print(head)
        print((len(head) 5)*"-")
        pass
  • Related