IF statement evaluating data from a CSV file

Hi forum.

I’m new to python and I’m trying to write a script to preform some actions based on information from a CSV file. I’m stuck at an IF statement, I want to evaluate if a specific cell has the text “Tracking #”, but even thought some cells have that value, it always returns as false.
What am I doing wrong? What is the correct way to do this IF statement?

import csv
import time
from selenium import webdriver
from selenium.webdriver.common.by import By

with open('TEST_1.csv', 'r') as csv_file:
    csv_reader= csv.reader(csv_file)

    for row in csv_reader:

        if row[8] == ["Tracking #"]:
            print("registered mail")
            print("normal mail")

If this was a screenshot of some output or error, please don’t do this.
Cut/paste the text directly into the message instead. Thanks!

You have:

for row in csv_reader:
    if row[8] == ["Tracking #"]:

Each row is a list of values, and in this case row[8] is a string.
You’re comparing it with a single element list containing one string.
They will therefore not be the same.

You just want to compare against a string, because you have a string:

if row[8] == "Tracking #":

You can get more insight into why things are not working by printing out
the values involved. For example, if you have put this:

print(repr(row[8]), repr(["Tracking #"]))

just before the if-statement this discrepancy would be more clear.

In fact, i recommend you do that before making the change to the
if-statement just to see if the issue beomces clear just from the print.

Cameron Simpson cs@cskk.id.au

1 Like