How to know if the incoming data is equal to the last row, first column of a CSV file

I'm reading some QR codes on Raspberry Pi, and I'm writing that data on a CSV file, but the problem is, when the data is received, it gets spammed in the CSV file, by that I mean that as soon as the QR code gets detected, it will keep writing the data on the CSV as long as the QR is being shown to the Cam, and I want that data to be written only once.

The CSV file contains only a header that says "Orders:". I'm writing inside that CSV, the data, date, and time, each in a column What I thought of, and tried to do but didn't work, is to check whether the data is equal to the first column of the last row of the CSV file, if so then pass, else write the data, as follows:

import csv
import cv2

cap = cv2.VideoCapture(0)
detector = cv2.QRCodeDetector()

from datetime import date, datetime

today = date.today()
date = today.strftime("%d-%b-%Y")

now = datetime.now()
timeRN = now.strftime("%H:%M:%S")

while True:

  _, img = cap.read()  
    data, bbox, _ = detector.detectAndDecode(img)
    
    if(bbox is not None):
        for i in range(len(bbox)):
            cv2.line(img, tuple(bbox[i][0]), tuple(bbox[(i+1) % len(bbox)][0]), color=(255,
                     0, 0), thickness=2)
        cv2.putText(img, data, (int(bbox[0][0][0]), int(bbox[0][0][1]) - 10), cv2.FONT_HERSHEY_SIMPLEX,
                    1, (255, 250, 120), 2)
    
    if 'OrderNr' in data:
        with open('Orders.csv', mode='a+') as csvfile:
            
            csvfileWriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
            reader = readline()[-1]       
            lastRow = reader[-1]
            firstColumn = reader[1]
            if data in firstColumn:
                pass
            else:
                csvfileWriter.writerow([data, date, timeRN]) 
        a, b, c, d = data.split(',')
        print("data: ", a)
        print(b)
        print(c)
        print(d)
        lcd_print(a, b, c, d)   #just a method to print on LCD
        pass   

When I try this, what i get is

lastRow = reader[-1]
IndexError: string index out of range

What am I doing wrong here? and is the way I'm doing it wrong? If yes, then is there any other way or simpler way to do what I'm trying to do?

EDIT: Code Edited


Solution 1:

You can keep a variable that always holds the latest data. If the newly read data is equal to that, you ignore it and write to the file otherwise.

The relevant code changes are below.

....

latest = None

while True:

  _, img = cap.read()  
    data, bbox, _ = detector.detectAndDecode(img)

    ....
    
    if 'OrderNr' in data:
        with open('Orders.csv', mode='a+') as csvfile:
            
            csvfileWriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)

            if data != latest:
                csvfileWriter.writerow([data, date, timeRN])
                latest = data