Click here to Skip to main content
15,353,587 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I have a problem. Code deletes used rows (WinningRows) and if I use the file again, and random number is equal for the used and deleted number (#), it is not finding the new one. Just ignoring.

What I have tried:

def generate():
    global winningRows
    filename = enterFile()
    noOfWinners = 5
    winningNumbers = []
    while len(winningNumbers) < noOfWinners:
        luckyNumber = random.randint(1, totalEntries)
        if luckyNumber not in winningNumbers:
    with open(filename, newline='\n') as entriesCSV:
        entriesDict = csv.DictReader(entriesCSV,dialect="excel")
        allRows = [row for row in entriesDict]
        winningRows = [row for row in allRows if int(row["#"]) in winningNumbers]
        nonWinningRows = [row for row in allRows if int(row["#"]) not in winningNumbers]
        for row in winningRows:
            winnerName = row["Name"]
            winnerID = row["ID"]
            winnerEmail = row["Email"]
            print(f"The winner is {winnerName}, ID {winnerID}, email {winnerEmail}")
    with open(filename, "w", newline='\n') as entriesCSV:
        writer = csv.DictWriter(entriesCSV, fieldnames=["#", "Name", "ID", "Email"])
Updated 8-Apr-22 1:12am

1 solution

You have basically three options, either
  • Keep track of used and deleted numbers in order to avoid their repeated generation.

  • Renumber the rows in the file.

  • Use the generated random number, say r, to get the rth row in the file (regardless of #).
qwerty qwerty 2022 8-Apr-22 7:28am
I would like to use "if", by saying if luckyNumber not equal # then pick the new one... But what about "Use the generated random number, say r, to get the rth row in the file (regardless of #)"? I can't even imagine how to realize it. By counting rows in the file every single time?
CPallini 8-Apr-22 7:36am
If you pick (and remove) that way the items of AllRows then you don't have even to bother about duplicates in random extractions: every time choose a number in the [0, len(AllRows)-1] range.
qwerty qwerty 2022 8-Apr-22 7:41am
And how do I find r?
CPallini 8-Apr-22 8:09am
r = random.randint(1, len(AllRows)-1)
qwerty qwerty 2022 8-Apr-22 8:25am
Should I interpret r as luckyNumber and AllRows as totalEntries? And what if AllRows[r] and r=random.randint(1, len(AllRows)-1)? In one case we don't know r, in other - AllRows. Sorry, I'm just a little bit confused.
Just in case, luckyNumber = random.randint(1, totalEntries) and totalEntries = len([row for row in csv.reader(open(filename))]) - 1
Maciej Los 8-Apr-22 11:16am
DanielSinoca 11-Apr-22 18:41pm
r = random.randint(1, len(AllRows)-1)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900