user11274990
user11274990

Reputation:

Python nested for loop not printing

I am trying to print a row of a csv file if an item is found in a csv.

  1. CSV looks like this:
    • Avatar Name,Player Name,Player Number
    • LarchDew15,Emily,1
    • Pinerain2,Hannah,2
    • xOakenMaidx,Madison,3
    • Grandidel,Jacob,4
    • Gened123,Micheal,5
    • Tufty98,Matthew,6
    • silverstar,Ashley,7

import csv



def player_number():

    # Opens CSV
    with open("battle_royale.csv") as csvfile:
        readCSV = csv.reader(csvfile, delimiter=',')  # extracts data from the file

        number = input("Member Number: ")

        # Looks to see if user number is in CSV file.
        found = False
        for column in readCSV:
            for x in column:
                if x == number:
                    found = True

        # If found prints out row
        if found:
            for row in readCSV:
                if number in row:
                    print(row)

    # Close input file
    csvfile.close()


def main():


    user = input("What do you want to do? ")

    playerNum = False

    # Find by Number
    if user == "b" or user == "B":
        playerNum = True
        if playerNum is True:
            player_number()


main()

Runs with no errors.

Upvotes: 0

Views: 99

Answers (2)

san
san

Reputation: 1515

I removed quite a few redundant clauses, this should do:

import csv

def player_number():

    # Opens CSV
    with open("battle_royale.csv") as csvfile:
        readCSV = csv.reader(csvfile, delimiter=',')  # extracts data from the file

        number = input("Member Number: ")

        for row in readCSV:
            for value in row:
                if value == number:
                    print(row)



def main():
    user = input("What do you want to do? ")

    # Find by Number
    if user == "b" or user == "B":
        player_number()


main()

Upvotes: 0

Amin
Amin

Reputation: 1028

When you read a csv file using csv.reader, it splits the file into a list of rows, and each element in the row becomes a string. So in your comparison

if x == number:

You actually want to cast number as a string:

if x == str(number)

Upvotes: 1

Related Questions