嵌套Python的循环不打印

时间:2019-08-10 20:34:35

标签: python python-3.x csv

如果要在csv中找到某项,我想打印一行csv文件。

  1. CSV看起来像这样:
    • 头像名称,玩家名称,玩家编号
    • LarchDew15,Emily,1
    • Pinerain2,Hannah,2
    • xOakenMaidx,Madison,3
    • Grandidel,Jacob,4
    • Gened123,Micheal,5
    • Tufty98,Matthew,6
    • 银星,阿什利,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()

运行没有错误。

2 个答案:

答案 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()