Reputation:
I am trying to print a row of a csv file if an item is found in a csv.
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
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
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