如果要在csv中找到某项,我想打印一行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()
运行没有错误。
答案 0 :(得分:1)
当您使用csv.reader
读取一个csv文件时,它会将文件拆分为一个行列表,并且该行中的每个元素都变成一个字符串。所以在您的比较中
if x == number:
您实际上想将number
转换为字符串:
if x == str(number)
答案 1 :(得分:0)
我删除了很多多余的子句,应该这样做:
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()