Click here to Skip to main content
15,894,343 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm totally new to Python. Just trying to figure out how to pick few, but not the same (unique by ID) winners from the .csv file. Anyone could help?
Here's my code that choose only one winner:

import random
import csv
import getpass
import datetime
import docx
 
totalEntries = 0
timestamp = ""
winnerName = "" # our winner's name
winnerID = "" # our winner's unique ID number
winnerEmail = "" # our winner's contact email
filename = "entries.csv"
 
currentUser = getpass.getuser()
 
def enterFile():
    global filename
    try:
        with open(filename, newline="") as openfile:
            pass
        return filename
    except FileNotFoundError:
        while True:
            print("What is the name of the CSV file containing giveaway entrants?")
            filename = input("")
            if ".csv" not in filename:
                filename += ".csv"
            try:
                with open(filename, newline="") as openfile:
                    pass
                return filename
            except FileNotFoundError:
                print(f"I don't recognize the filename '{filename}' in the local directory. Please try again.")
 
def generate():
    global filename, totalEntries, timestamp, winnerName, winnerID, winnerEmail
    filename = enterFile()
 
    now = datetime.datetime.now()
    timestamp = now.strftime("%B %d, %Y %I:%M:%S %p")
 
    with open(filename, newline="") as entriesCSV:
        entriesDict = csv.reader(entriesCSV,dialect="excel")
 
        totalEntries = len(list(entriesDict)) - 1 # ignore our header row
 
    winningNumber = random.randint(1,totalEntries)
 
    with open(filename, newline="") as entriesCSV:
        entriesDict = csv.DictReader(entriesCSV,dialect="excel")
 
        for row in entriesDict:
            if int(row["#"]) == winningNumber:
                winnerName = row["Name"]
                winnerID = row["ID"]
                winnerEmail = row["Email"]
                print(f"The winner is {winnerName}, ID {winnerID}, email {winnerEmail}")
 
def createAuditSheet():
    doc = docx.Document()
    doc.add_paragraph("Giveaway: __________________________________________________________________________________________")
    doc.add_paragraph("______________________________________________________________________________________________________")
    doc.add_paragraph("Prize: _______________________________________________________________________________________________")
    doc.add_paragraph(f"The winner is {winnerName}, ID {winnerID}, email {winnerEmail}.")
    doc.add_paragraph(f"Drawn {timestamp} by user {currentUser} from {totalEntries} total entries found in file {filename}")
    for i in range(5):
        doc.add_paragraph("")
    doc.add_paragraph("Signature _________________________________________________________________ Date ___________________")
    doc.add_paragraph("Pick Up Date ___________________")
    doc.save("GiveawayDrawingResults.docx")
 
generate()
createAuditSheet()
print("Task completed.")


Algorithm I'd like to use:

1. Open csv file
2. Pick chosen number of winners
3. Print and save them to docx
4. Delete them from csv
5. Close csv file

What I have tried:

What have I tried - edited the generation function to make it choose 5 winners (unfortunately, it didn't worked):

def generate():
    filename = enterFile()
 
    noOfWinners = 5
    winningNumbers = []
    while len(winningNumbers) < noOfWinners:
        luckyNumber = random.randint(1, totalEntries - 1)
        if luckyNumber not in winningNumbers:
            winningNumbers.append(luckyNumber)
 
    with open(filename, newline="") as entriesCSV:
        entriesDict = csv.DictReader(entriesCSV,dialect="excel")
 
        for number in winningNumbers:
            for row in entriesDict:
                if int(row["#"]) == number:
                    winnerName = row["Name"]
                    winnerID = row["ID"]
                    winnerEmail = row["Email"]
                    print(f"The winner is {winnerName}, ID {winnerID}, email {winnerEmail}")
Posted
Comments
Richard MacCutchan 7-Apr-22 10:05am    
"unfortunately, it didn't worked"
Sadly, we cannot read minds, so we have no idea what that means. Please use the Improve question link above, and add complete details of what is not working.
[no name] 7-Apr-22 12:09pm    
Write the csv (entriesDict) contents back to storage; using the "winningNumbers" to filter the row # while writing.

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



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